1. 概念
- 左外连接:left join左边的是主表;
- 右外连接:right join右边的是主表;
- 左外连接和右外连接交换两个表的顺序,可以实现相同的效果;
2. 示例
(1)查询男朋友不在男生表的女生名----------左外连接
SELECT
b.name
FROM
beauty b
LEFT
OUTER JOIN
boys bo
ON
b.`boyfriend_id`=bo.`id`
WHERE
bo.`id` IS NULL;
(2)查询男朋友不在男生表的女生名----------右外连接
SELECT
b.name
FROM
boys bo
RIGHT
OUTER JOIN
beauty b
ON
b.`boyfriend_id`=bo.`id`
WHERE
bo.`id` IS NULL;
(3)查询哪个部门没有员工-----------------左外连接
SELECT
d.*,
e.employee_id
FROM
`departments` d
LEFT OUTER JOIN
`employees` e
ON
d.`department_id`=e.`department_id`
WHERE
e.`department_id` IS NULL;
(4)查询哪个部门没有员工-----------------右外连接
SELECT
d.*,
e.employee_id
FROM
`employees` e
RIGHT OUTER JOIN
`departments` d
ON
d.`department_id`=e.`department_id`
WHERE
e.`department_id` IS NULL;