一、概念
left join(左连接):返回包括左表中的所有记录和右表中连接字段相等的记录。
right join(右连接):返回包括右表中的所有记录和左表中连接字段相等的记录。
inner join(内连接):只返回两个表中连接字段相等的行。
full join (全外连接):返回左右表中所有的记录和左右表中连接字段相等的记录。
概念理解起来比较困难的话,我们用一个图来表示:
![](https://img.haomeiwen.com/i3791135/1b49b8ae49bc2679.png)
二、上手使用
首先,我这里用了两个表,表之间没有什么联系,只是为了演示所用。
表1数据:
![](https://img.haomeiwen.com/i3791135/e9cc7905754842c1.png)
表2数据
![](https://img.haomeiwen.com/i3791135/b396ee5b97b47e34.png)
left join(左连接)
![](https://img.haomeiwen.com/i3791135/da91846e5143048b.png)
-- left join:返回包括左表中的所有记录和右表中连接字段相等的记录
select * from t_user t1 left join t_role t2 on t1.id = t2.id;
展示结果集如下:
![](https://img.haomeiwen.com/i3791135/cc44777bba2ade63.png)
rint join(右连接)
![](https://img.haomeiwen.com/i3791135/85aed79b7d367990.png)
-- right join:返回包括右表中的所有记录和左表中连接字段相等的记录。
select * from t_user t1 right join t_role t2 on t1.id = t2.id;
展示结果集如下:
![](https://img.haomeiwen.com/i3791135/c3bf5bb0cf2fa5cb.png)
inner join(内连接,等同join)
![](https://img.haomeiwen.com/i3791135/963ca2d6244c3cc0.png)
-- inner join:只返回两个表中连接字段相等的行。
select * from t_user t1 inner join t_role t2 on t1.id = t2.id;
展示结果集如下:
![](https://img.haomeiwen.com/i3791135/ef3caf434006d31c.png)
full join(全连接,等同full outer join)
![](https://img.haomeiwen.com/i3791135/55aaf7249d993101.png)
-- 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://img.haomeiwen.com/i3791135/b3e9416c30544503.png)
————————————————
原文链接:https://blog.csdn.net/u011047968/article/details/107744901
网友评论