Mysql 的七种 join
作 者:
原文链接:https://www.hchstudio.cn/article/2017/56cd/
版权声明:非特殊声明均为本站原创作品,转载时请注明作者和原文链接。
对于SQL的Join,在学习起来可能是比较乱的。我们知道,SQL的Join语法有很多inner的,有outer的,有left的,有时候,对于Select出来的结果集是什么样子有点不是很清楚。Coding Horror上有一篇文章(实在不清楚为什么Coding Horror也被墙)通过 文氏图 Venn diagrams解释了SQL的Join。
建表
在这里呢我们先来建立两张有外键关联的张表。
1 | CREATE DATABASE db0206; |
文氏图与SQL语句的编写以及查询结果
内连接
内连接文氏图

执行的sql语句以及执行的查询结果
执行的sql语句
1
select * from tbl_dept a inner join tbl_emp b on a.id=b.deptId;
查询结果

左外连接
左外连接文氏图

执行的sql语句以及执行的查询结果
- 执行的sql语句
1 | select * from tbl_dept a left join tbl_emp b on a.id=b.deptId; |
- 查询结果

右外连接
右外连接文氏图

执行的sql语句以及执行的查询结果
- 执行的sql语句
1 | select * from tbl_dept a right join tbl_emp b on a.id=b.deptId; |
- 查询结果

左连接
左连接文氏图

执行的sql语句以及执行的查询结果
- 执行的sql语句
1 | elect * from tbl_dept a left join tbl_emp b on a.id=b.deptId where b.deptId is null; |
- 查询结果

右连接
右连接文氏图

执行的sql语句以及执行的查询结果
- 执行的sql语句
1 | select * from tbl_dept a right join tbl_emp b on a.id=b.deptId where a.id is null; |
- 查询结果

全连接
全连接文氏图

执行的sql语句以及执行的查询结果
- 执行的sql语句
1 | select * from tbl_dept a right join tbl_emp b on a.id=b.deptId |
- 查询结果

两张表中都没有出现的数据集
文氏图

执行的sql语句以及执行的查询结果
- 执行的sql语句
1 | select * from tbl_dept a right join tbl_emp b on a.id=b.deptId where a.id is null union select * from tbl_dept a left join tbl_emp b on a.id=b.deptId where b.deptId is null; |
- 查询结果


作 者:
原文链接:https://www.hchstudio.cn/article/2017/56cd/
版权声明:非特殊声明均为本站原创作品,转载时请注明作者和原文链接。
