MySQL的两张表的七种Join查询

SQL的语法格式如下

SELECT DISTINCT
	< select_list > 
FROM
	< left_table > < join_type >
JOIN < right_table > ON <join_condition>
WHERE
	< where_condition > 
GROUP BY
	< group_by_list > 
HAVING
	< having_condition > 
ORDER BY
	< order_by_condition > 
LIMIT < limit_number >

想掌握最基础的三个:left join、right join、inner join

假设有A表和B表两张表 

A表:id、员工名、部门号
id name dept_no
1 张三 1
2 李四 2

B表:主键id、部门名、部门主管
dept_no dept_name dept_admin
2 人力资源部 李四
3 财务部 null

 我们都知道数据库在进行表连接即(join)操作的时候,是进行笛卡尔积操作

A表两行记录,B表两行记录。进行迪卡积就变成2 x 2=4行记录

(不考虑数据真实性)假设如上A、B两张表进行笛卡尔积操作结果就是如下

id name dept_no dept_no dept_name dept_admin
1 张三 1 2 人力资源部 李四
1 张三 1 2 人力资源部 李四
2 李四 2 3 财务部 null
2 李四 2 3 财务部 null

第一个是左连接:A Left Join B   得到集合(A)

left join 特点是保留A表所有字段,如果没有匹配到连接条件则用null填充

对应sql示例

select A.*,B.* from A left join B on A.dept_no=B.dept_no;

结果如下:

id name dept_no dept_no dept_name dept_admin
2 李四 2 2 人力资源部 李四
1 张三 1 null null null

 图示:


 第二个是右连接 A right join B   得到集合(B)

sql示例: 

select A.*,B.* from A right join B on A.dept_no=B.dept_no;

结果如下:

id name dept_no dept_no dept_name dept_admin
2 李四 2 2 人力资源部 李四
null null null 3 财务部 null

图示:


第三个是 内连接 A inner join B   得到(A∩B)

SQL示例 

select A.*,B.* from A right join B on A.dept_no=B.deptno;

 对应结果就是:

id name dept_no dept_no dept_name dept_admin
2 李四 2 2 人力资源部 李四

 图示:


 第四种:在理解上面的三种join下,查询(A -  A∩B)

对应图示:

sql示例:实际上只是加入where条件过滤

select A.*,B.* from A left join B on A.dept_no=B.deptno where B.dept_no is null;
id name dept_no dept_no dept_name dept_admin
2 李四 2 2 人力资源部 李四

第五种:查询 ( B - A∩B )

图示:

sql示例:

select A.*,B.* from A right join B on A.dept_no=B.deptno where A.dept_no is null;
id name dept_no dept_no dept_name dept_admin
2 李四 2 2 人力资源部 李四

 第六种:查询(A∪B - A∩B)

图示:

sql示例:利用union去重将上面的第四、第五种两条sql中间用union连接即可完成;即先完成一小部分的,然后将两个拼起来的思想

select A.*,B.* from A left join B on A.dept_no=B.deptno where B.dept_no is null
union
select A.*,B.* from A right join B on A.dept_no=B.deptno where A.dept_no is null;

结果:

id name dept_no dept_no dept_name dept_admin
1 张三 1 null null null
null null null 3 财务部 null

 第七种:AUB

图示:

sql示例 

select a.*,b.* from a left join b on a.dept_no=b.dept_no
UNION
select a.*,b.* from a right join b on a.dept_no=b.dept_no;
id name dept_no dept_no dept_name dept_admin
2 李四 2 2 人力资源部 李四
1 张三 1 null null null
null null null 3 财务部 null
发布了302 篇原创文章 · 获赞 37 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41813208/article/details/105463918
今日推荐