mysql七种常用的JOIN查询
1 A、B两表共有
select * from tbl_emp a inner join tbl_dept b on a.deptId = b.id;
2 A、B两表共有+A的独有
select * from tbl_emp a left join tbl_dept b on a.deptId = b.id;
3 A、B两表共有+B的独有
select * from tbl_emp a right join tbl_dept b on a.deptId = b.id;
4 A的独有
select * from tbl_emp a left join tbl_dept b on a.deptId = b.id where b.id is null;
5 B的独有
select * from tbl_emp a right join tbl_dept b on a.deptId = b.id where a.deptId is null; #B的独有
6 AB全有
#MySQL Full Join的实现 因为MySQL不支持FULL JOIN,下面是替代方法
#left join + union(可去除重复数据)+ right join
SELECT * FROM tbl_emp A LEFT JOIN tbl_dept B ON A.deptId = B.id
UNION
SELECT * FROM tbl_emp A RIGHT JOIN tbl_dept B ON A.deptId = B.id
7 A的独有+B的独有
SELECT * FROM tbl_emp A LEFT JOIN tbl_dept B ON A.deptId = B.id WHERE B.`id` IS NULL
UNION
SELECT * FROM tbl_emp A RIGHT JOIN tbl_dept B ON A.deptId = B.id WHERE A.`deptId` IS NULL;