Mysql两表 join 查询方式
Posted 大猩猩爱分享
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql两表 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;
2. right join(右连接)
A right join B 得到B表所有的字段
select A.*,B.* from A right join B on A.id=B.id;
3. inner join(内连接)
A inner join B得到(A和B的交集)
select A.*,B.* from A inner join B on A.id=B.id;
4. 在理解上面的三种join下,查询(A - A∩B)
select A.*,B.* from A left join B on A.id=B.id where B.id is null;
5. 查询 ( B - A∩B )
select A.*,B.* from A right join B on A.id=B.id where A.id is null;
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;
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查询
1 A、B两表共有
select * from tbl_emp a inner join tbl_dept b on a.deptId = b.id;
2 A、B两表共有+A的独有
select * from tbl_emp a left join tbl_dept b on a.deptId = b.id;
3 A、B两表共有+B的独有
select * from tbl_emp a right join tbl_dept b on a.deptId = b.id;
4 A的独有
select * from tbl_emp a left join tbl_dept b on a.deptId = b.id where b.id is null;
5 B的独有
select * from tbl_emp a right join tbl_dept b on a.deptId = b.id where a.deptId is null; #B的独有
6 AB全有
#MySQL Full Join的实现 因为MySQL不支持FULL JOIN,下面是替代方法
#left join + union(可去除重复数据)+ right join
SELECT * FROM tbl_emp A LEFT JOIN tbl_dept B ON A.deptId = B.id
UNION
SELECT * FROM tbl_emp A RIGHT JOIN tbl_dept B ON A.deptId = B.id
7 A的独有+B的独有
SELECT * FROM tbl_emp A LEFT JOIN tbl_dept B ON A.deptId = B.id WHERE B.`id` IS NULL
UNION
SELECT * FROM tbl_emp A RIGHT JOIN tbl_dept B ON A.deptId = B.id WHERE A.`deptId` IS NULL;
以上是关于Mysql两表 join 查询方式的主要内容,如果未能解决你的问题,请参考以下文章