MySQL 在外连接中用 or 逻辑

备注:测试数据库版本为MySQL 8.0

一.需求

返回部门10 和 20中所有员工的姓名和部门信息,并返回部门30和40(但不包含员工信息)的部门信息。

二.解决方案

将 OR 条件移到 JOIN子句中:

select e.ename, d.deptno, d.dname, d.loc
from dept d
left join emp e
on (d.deptno = e.deptno
and (e.deptno = 10 or e.deptno = 20)
)
order by 2;

另外,还可以先用 emp.deptno 进行筛选,然后进行外部联接":

select e.ename, d.deptno, d.dname, d.loc
from dept d
left join
( select ename , deptno
from emp
where deptno in (10,20)
) e on (e.deptno = d.deptno)
order by 2;

测试记录

mysql> select e.ename, d.deptno, d.dname, d.loc
    ->    from dept d
    ->      left join emp e
    ->       on (d.deptno = e.deptno
    ->       and (e.deptno = 10 or e.deptno = 20)
    ->       )
    -> order by 2;
+--------+--------+------------+----------+
| ename  | deptno | dname      | loc      |
+--------+--------+------------+----------+
| CLARK  |     10 | ACCOUNTING | NEW YORK |
| KING   |     10 | ACCOUNTING | NEW YORK |
| MILLER |     10 | ACCOUNTING | NEW YORK |
| SMITH  |     20 | RESEARCH   | DALLAS   |
| JONES  |     20 | RESEARCH   | DALLAS   |
| SCOTT  |     20 | RESEARCH   | DALLAS   |
| ADAMS  |     20 | RESEARCH   | DALLAS   |
| FORD   |     20 | RESEARCH   | DALLAS   |
| NULL   |     30 | SALES      | CHICAGO  |
| NULL   |     40 | OPERATIONS | BOSTON   |
+--------+--------+------------+----------+
10 rows in set (0.01 sec)
mysql>
mysql> select e.ename, d.deptno, d.dname, d.loc
    ->    from dept d
    ->    left join
    ->          ( select ename , deptno
    ->              from emp
    ->            where deptno in (10,20)
    ->          ) e on (e.deptno = d.deptno)
    -> order by 2;
+--------+--------+------------+----------+
| ename  | deptno | dname      | loc      |
+--------+--------+------------+----------+
| CLARK  |     10 | ACCOUNTING | NEW YORK |
| KING   |     10 | ACCOUNTING | NEW YORK |
| MILLER |     10 | ACCOUNTING | NEW YORK |
| SMITH  |     20 | RESEARCH   | DALLAS   |
| JONES  |     20 | RESEARCH   | DALLAS   |
| SCOTT  |     20 | RESEARCH   | DALLAS   |
| ADAMS  |     20 | RESEARCH   | DALLAS   |
| FORD   |     20 | RESEARCH   | DALLAS   |
| NULL   |     30 | SALES      | CHICAGO  |
| NULL   |     40 | OPERATIONS | BOSTON   |
+--------+--------+------------+----------+
10 rows in set (0.00 sec)

你可能感兴趣的:(#,MySQL,CookBook,MySQL从小工到专家之路,mysql,sql,外连接,or,临时表)