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>
機(jī)讀(MySQL讀取順序)
機(jī)讀順序
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的獨(dú)有
select * from tbl_emp a left join tbl_dept b on a.deptId = b.id
3、A、B兩表共有+B的獨(dú)有
select * from tbl_emp a right join tbl_dept b on a.deptId = b.id;
4、A的獨(dú)有
select * from tbl_emp a left join tbl_dept b on a.deptId = b.id where b.id is null;
5、B的獨(dú)有
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的實(shí)現(xiàn) 因?yàn)镸ySQL不支持FULL JOIN,下面是替代方法
left join + union(可去除重復(fù)數(shù)據(jù))+ right join
實(shí)現(xiàn)如下面代碼
7、A的獨(dú)有 + B的獨(dú)有
-- 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的獨(dú)有 + B的獨(dú)有
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;