mysql 左连接、右连接、内连接、全外连接的区别

一、概念

left join(左连接):返回包括左表中的所有记录和右表中连接字段相等的记录。
right join(右连接):返回包括右表中的所有记录和左表中连接字段相等的记录。
inner join(内连接):只返回两个表中连接字段相等的行。
full join (全外连接):返回左右表中所有的记录和左右表中连接字段相等的记录。

概念理解起来比较困难的话,我们用一个图来表示:
在这里插入图片描述

二、上手使用

首先,我这里用了两个表,表之间没有什么联系,只是为了演示所用。

表1数据:

在这里插入图片描述

表2数据

在这里插入图片描述

left join(左连接)

在这里插入图片描述

-- left join:返回包括左表中的所有记录和右表中连接字段相等的记录
select * from t_user t1 left join t_role t2 on t1.id = t2.id;

展示结果集如下:
在这里插入图片描述

rint join(右连接)

在这里插入图片描述


-- right join:返回包括右表中的所有记录和左表中连接字段相等的记录。
select * from t_user t1 right join t_role t2 on t1.id = t2.id;

展示结果集如下:
在这里插入图片描述

inner join(内连接,等同join)

在这里插入图片描述

-- inner join:只返回两个表中连接字段相等的行。
select * from t_user t1 inner join t_role t2 on t1.id = t2.id;

展示结果集如下:
在这里插入图片描述

full join(全连接,等同full outer join)

在这里插入图片描述

-- mysql不支持full join
select * from t_user t1 full join t_role t2 on t1.id = t2.id;

如果使用以上sql则会报错:

[SQL]select * from t_user t1 full outer join t_role t2 on t1.id = t2.id;
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'full outer join t_role t2 on t1.id = t2.id' at line 1

mysql中可以使用union all加左右连接实现full join的效果

-- mysql的full join:返回左右表中所有的记录和左右表中连接字段相等的记录。
select	* from t_user t1 left join t_role t2 on t1.id = t2.id 
union all
select * from t_user t1 right join t_role t2 on t1.id = t2.id where t1.id is null

展示结果集如下:
在这里插入图片描述
————————————————
版权声明:本文为CSDN博主「leo825…」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011047968/article/details/107744901

猜你喜欢

转载自blog.csdn.net/fth1002853070/article/details/131625817