在上一篇文章中,我们建了两张表:tbl_dept,tbl_emp,并向这两张表插入了一些数据,在这篇文章中,我们借用前面的两张表,研究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 and 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;
6、AB全有
select * from tbl_emp a full outer 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;
以上是对7中join的总结,具体使用哪种,需要根据具体情况而定。