概念
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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/72679.html