MYSQL语法:左连接、右连接、内连接、全外连接

概念

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

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

上手使用

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

left join(左连接)

左连接

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

展示结果集如下:
结果集1

rint join(右连接)

右连接

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

展示结果集如下:
结果2

inner join(内连接,等同join)

内连接

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

展示结果集如下:
结果集3

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

展示结果集如下:
结果集4

猜你喜欢

转载自blog.csdn.net/u011047968/article/details/107744901