目录
- MySQL内连接、左连接、右连接、外连接、多表查询
- 构建环境:
- 一、INNERJION内连接(A∩B)
- 二、LEFTJOIN左外连接(A全有)
- 三、RIGHTJOIN右外连接(B全有)
- 四、FULLJOIN全外连接(A+B)
- 五、LEFTExcludingJOIN(A-B即A表独有)+
- 六、RIGHTExcludingJOIN(B-A即B表独有)
- 七、OUTERExcludingJOIN(A与B各自独有)
- 总结
MySQL 内连接、左连接、右连接、外连接、多表查询
构建环境:
create table t_emp( id int primary key, name varchar(20), deptId int ); create table t_dept( id int primary key, name varchar(20) ); insert into t_dept(id, name) values(1, '设计部'); insert into t_dept(id, name) values(2, '开发部'); insert into t_dept(id, name) values(3, '测试部'); insert into t_emp(id, name, deptId) values(1, '张三', 1); insert into t_emp(id, name, deptId) values(2, '李四', 2); insert into t_emp(id, name, deptId) values(3, '王五', 0); # ps:为了说明方便,t_emp 表 说成 A 表, t_dept 表说成 B 表
目录
一、INNER JION 内连接 ( A ∩ B )
SELECT * FROM t_emp e INNER JOIN t_dept d ON e.deptId = d.id;
二、LEFT JOIN 左外连接( A 全有 )
SELECT * FROM t_emp e LEFT JOIN t_dept d ON e.deptId = d.id;
三、RIGHT JOIN 右外连接 (B 全有)
SELECT * FROM t_emp e RIGHT JOIN t_dept d ON e.deptId = d.id;
四、FULL JOIN 全外连接( A + B)
SELECT * FROM t_emp e LEFT JOIN t_dept d ON e.deptId = d.id UNION SELECT * FROM t_emp e RIGHT JOIN t_dept d ON e.deptId = d.id;
五、LEFT Excluding JOIN ( A – B 即 A 表独有)+
SELECT * FROM t_emp e LEFT JOIN t_dept d ON e.deptId= d.id WHERE d.id is null;
六、RIGHT Excluding JOIN ( B – A 即 B表独有)
SELECT * FROM t_emp e RIGHT JOIN t_dept d ON e.deptId= d.id WHERE e.id is null;
七、OUTER Excluding JOIN (A 与 B 各自独有)
SELECT * FROM t_emp e LEFT JOIN t_dept d ON e.deptId= d.id WHERE d.id is null UNION SELECT * FROM t_emp e RIGHT JOIN t_dept d ON e.deptId= d.id WHERE e.id is null;
总结
本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注NICE源码的更多内容!