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>
机读(MySQL读取顺序)
机读顺序
FROM
<left_table>
ON <join_condition>
<join_type> JOIN <right_table>
WHERE
<where_condition>
GROUP BY
<group_by_list>
HAVING
<having_condition>
SELECT DISTINCT
<select_list>
ORDER BY
<order_by_condition>
LIMIT <limit_number>
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;
6、AB全有
MySQL Full Join的实现 因为MySQL不支持FULL JOIN,下面是替代方法
left join + union(可去除重复数据)+ right join
实现如下面代码
7、A的独有 + B的独有
-- 6、AB全有
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;