服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Mysql - 详解Mysql两表 join 查询方式

详解Mysql两表 join 查询方式

2022-11-28 15:01LoveDR_1995 Mysql

这篇文章主要介绍了Mysql两表 join 查询方式,主要包括SQL基本语法格式ji3种join方式,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下

一、SQL基本语法格式

SELECT DISTINCT
	< select_list > 
FROM
	< left_table > < join_type >
JOIN < right_table > ON <join_condition>
WHERE
	< where_condition > 
GROUP BY
	< group_by_list > 
HAVING
	< having_condition > 
ORDER BY
	< order_by_condition > 
LIMIT < limit_number >

二、3种join方式

1. left join(左连接)

A left join B 得到A表的所有字段,如果没有匹配到连接条件则用null填充

select A.*,B.* from A left join B on A.id = B.id;

详解Mysql两表 join 查询方式

2. right join(右连接)

A right join B 得到B表所有的字段

select A.*,B.* from A right join B on A.id=B.id;

详解Mysql两表 join 查询方式

3. inner join(内连接)

A inner join B得到(A和B的交集)

select A.*,B.* from A inner join B on A.id=B.id;

详解Mysql两表 join 查询方式

4. 在理解上面的三种join下,查询(A -  A∩B)

select A.*,B.* from A left join B on A.id=B.id where B.id is null;

详解Mysql两表 join 查询方式

 5. 查询 ( B - A∩B )

select A.*,B.* from A right join B on A.id=B.id where A.id is null;

详解Mysql两表 join 查询方式

 6. 查询(A∪B - A∩B)

利用union去重将上面的第四、第五种两条sql中间用union连接即可完成;即先完成一小部分的,然后将两个拼起来的思想。

select A.*,B.* from A left join B on A.id=B.id where B.id is null
union
select A.*,B.* from A right join B on A.id=B.id where A.id is null;

详解Mysql两表 join 查询方式

 7. 查询 AUB

MySQL中求并集可以使用union关键字进行处理(自动去重)

select A.*,B.* from A left join B on A.id=B.id
UNION
select A.*,B.* from A right join B on A.id=B.id;

详解Mysql两表 join 查询方式

到此这篇关于Mysql两表 join 查询方式的文章就介绍到这了,更多相关Mysql join 查询内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://blog.csdn.net/xrq1995/article/details/127427289

延伸 · 阅读

精彩推荐