三表左连接(LEFT JOIN)
问题:
最近遇到需求多表连接,要求A表所有数据均展示,B表和C表关联A表,若A表有的B,C表没有则展示为null,由此引发以下问题:文章来源地址https://www.toymoban.com/news/detail-400985.html
- A表作为基表,先关联B表,关联条件为A.userId=B.userId;
- 再关联C表,关联条件是A.userId=C.userId还是B.userId=C.userId呢?这两个条件有什么区别吗?
测试:
- 建表:user_info
- A表:
(select userId,count(*) as count1 from user_info where userName is not null group by userId) A
结果:包含userId为1,2,3,4的数据
- B表:
(select userId,count(*) as count2 from user_info where userName='tom' group by userId) b
结果:包含userId为1,3,4的数据
- C表:
select userId,count(*) as count3 from user_info where userId>1 group by userId
结果:包含userId为2,3,4的数据
第一种连接方式
- 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
- 结果:
第二种连接方式
- 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
- 结果:
结论
- 第一种连接方式:A,B表连接时,A表作为基表,故A表中的数据全部显示,B表中userId为1,3,4时正常显示,为2时自动补null值;A,C表连接时,A表仍然为基表,当userId为2,3,4时C表正常显示,为1时自动补null值。
- 第二种连接方式:A,B表连接时,与第一种连接方式相同;B,C表连接时,此时B表为基表,由于B表没有userId为2的值,故C表的userId为2的值也不显示,故C表只显示userId为3,4的数据。
文章来源:https://www.toymoban.com/news/detail-400985.html
到了这里,关于三表左连接(LEFT JOIN) — 两表之间的关系的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!