美文网首页
Mysql 左连接、右连接、内连接、全外连接

Mysql 左连接、右连接、内连接、全外连接

作者: R_X | 来源:发表于2023-07-08 18:37 被阅读0次

一、概念

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

概念理解起来比较困难的话,我们用一个图来表示:


image.png

二、上手使用

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

表1数据:

image.png

表2数据

image.png

left join(左连接)

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

展示结果集如下:


image.png

rint join(右连接)

image.png

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

展示结果集如下:


image.png

inner join(内连接,等同join)

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

展示结果集如下:


image.png

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

展示结果集如下:

全外连接
————————————————
原文链接:https://blog.csdn.net/u011047968/article/details/107744901

相关文章

网友评论

      本文标题:Mysql 左连接、右连接、内连接、全外连接

      本文链接:https://www.haomeiwen.com/subject/mhjjudtx.html