MySQL 七种 JOIN

共有
SELECT
    *
FROM
    t_dept a
INNER JOIN t_emp b ON a.id = b.deptId;

左独占+共有

SELECT
    *
FROM
    t_dept a
LEFT JOIN t_emp b ON a.id = b.deptId;

右独占+共有

SELECT
    *
FROM
    t_dept a
RIGHT JOIN t_emp b ON a.id = b.deptId;

左独占

SELECT
    *
FROM
    t_dept a
LEFT JOIN t_emp b ON a.id = b.deptId
WHERE b.deptId IS NULL;

右独占

SELECT
    *
FROM
    t_dept a
RIGHT JOIN t_emp b ON a.id = b.deptId
WHERE a.id IS NULL;

左右全部

SELECT
    *
FROM
    t_dept a
LEFT JOIN t_emp b ON a.id = b.deptId
UNION
SELECT
    *
FROM
    t_dept a
RIGHT JOIN t_emp b ON a.id = b.deptId;

左独占+右独占

SELECT
    *
FROM
    t_dept a
LEFT JOIN t_emp b ON a.id = b.deptId
WHERE b.deptId IS NULL 
UNION
SELECT
    *
FROM
    t_dept a
RIGHT JOIN t_emp b ON a.id = b.deptId
WHERE a.id IS NULL;

相关推荐