三表左连接(LEFT JOIN) — 两表之间的关系

三表左连接(LEFT JOIN)

问题:

  最近遇到需求多表连接,要求A表所有数据均展示,B表和C表关联A表,若A表有的B,C表没有则展示为null,由此引发以下问题:

  1. A表作为基表,先关联B表,关联条件为A.userId=B.userId;
  2. 再关联C表,关联条件是A.userId=C.userId还是B.userId=C.userId呢?这两个条件有什么区别吗?

测试:

  1. 建表:user_info
    在这里插入图片描述
  2. A表:
    (select userId,count(*) as count1 from user_info where userName is not null group by userId) A
    结果:包含userId为1,2,3,4的数据
    在这里插入图片描述
  3. B表:
    (select userId,count(*) as count2 from user_info where userName='tom' group by userId) b
    结果:包含userId为1,3,4的数据
    在这里插入图片描述
  4. C表:
    select userId,count(*) as count3 from user_info where userId>1 group by userId
    结果:包含userId为2,3,4的数据
    在这里插入图片描述

第一种连接方式

  1. A表作为基表,连接条件选择:A.userId=B.userId   A.userId=C.userId
select a.userId,a.count1,b.count2,c.count3 from 
(select userId,count(*) as count1 from user_info where userName is not null group by userId) a
left join
(select userId,count(*) as count2 from user_info where userName='tom' group by userId) b
on a.userId = b.userId
left join
(select userId,count(*) as count3 from user_info where userId>1 group by userId) c
on a.userId = c.userId
  1. 结果:
    在这里插入图片描述

第二种连接方式

  1. A表作为基表,连接条件选择:A.userId=B.userId   B.userId=C.userId
select a.userId,a.count1,b.count2,c.count3 from 
(select userId,count(*) as count1 from user_info where userName is not null group by userId) a
left join
(select userId,count(*) as count2 from user_info where userName='tom' group by userId) b
on a.userId = b.userId
left join
(select userId,count(*) as count3 from user_info where userId>1 group by userId) c
on b.userId = c.userId
  1. 结果:
    在这里插入图片描述

结论

  1. 第一种连接方式:A,B表连接时,A表作为基表,故A表中的数据全部显示,B表中userId为1,3,4时正常显示,为2时自动补null值;A,C表连接时,A表仍然为基表,当userId为2,3,4时C表正常显示,为1时自动补null值。
  2. 第二种连接方式:A,B表连接时,与第一种连接方式相同;B,C表连接时,此时B表为基表,由于B表没有userId为2的值,故C表的userId为2的值也不显示,故C表只显示userId为3,4的数据。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>