前言
有时候为了得到完整的结果,我们需要对两个及其以上的表进行操作,所以本文就几种常见的join操作进行了总结。
一、实验数据
两张表:部门表与员工表
- 部门表
- 员工表
二、7种情况
情况1
查询两张表共有的部分
select * from tbl_dept a
-> inner join
-> tbl_emp b
-> on
-> a.id = b.deptId;
情况2(Left Join)
查询A表独有且A、B两表共有的部分
select * from tbl_dept a
-> left join
-> tbl_emp b
-> on
-> a.id = b.deptId;
情况3(Right Join)
查询B表独有且A、B两表共有的部分
select * from tbl_dept a
-> right join
-> tbl_emp b
-> on
-> a.id = b.deptId;
情况4
A表独有的部分
select * from tbl_dept a
-> left join
-> tbl_emp b
-> on a.id = b.deptId
-> where
-> b.deptId is null;
情况5
B表独有的部分
select * from tbl_dept a
-> right join
-> tbl_emp b
-> on
-> a.id = b.deptId
-> where
-> a.id is null;
情况6 (Full Join)
A、B两表的全部
PS:mysql不支持全链接,故使用union关键字
select * from tbl_dept a left join tbl_emp b on a.id=b.deptId
-> union
-> select * from tbl_dept a right join tbl_emp b on a.id=b.deptId;
情况7
A表独有的部分和B表独有的部分
select * from tbl_dept a left join tbl_emp b on a.id = b.deptId where b.deptId is null
union
select * from tbl_dept a right join tbl_emp b on a.id = b.deptId where a.id is null;