数据库
首页 > 数据库> > mysql-为什么此左外部联接产生错误结果?

mysql-为什么此左外部联接产生错误结果?

作者:互联网

我对以下关于OUTER JOIN的SQL(也许是微不足道的)感到困惑.
我有2个小表emp和deptno,即具有员工及其部门记录的表.他们的关系显然是1-N(但这无关紧要).
我正在尝试使用外部联接来查找没有员工在那里工作的部门.所以我认为正确的解决方案是外部联接.
如果我执行以下操作:

select d.deptno as d_deptno, e.deptno as e_deptno  
from dept d left outer join  emp e  
on d.deptno = e.deptno;    

我得到:

d_deptno    e_deptno  
10,         10  
10,         10  
10,         10  
20,         20  
20,         20  
20,         20  
20,         20  
20,         20   
30,         30  
30,         30  
30,         30   
30,         30  
30,         30  
30,         30  
40,         null    

好的,所以我认为我需要的只是最后一行,因此我只需要按如下方式修改查询:

select d.deptno as d_deptno, e.deptno as e_deptno  
from dept d left outer join  emp e  
on d.deptno = e.deptno and e.deptno is null;  

即我添加了e.deptno为空.由于某些原因,如果我的e_deptno为null,则无法解析查询(为什么?)
但是我得到的结果如下!

d_deptno  e_deptno  
10,       null   
20,       null   
30,       null   
40,       null   

为什么我得到这些结果?我对OUTER JOIN的误解是什么?

解决方法:

条件e.deptno为null需要在where子句中:

select d.deptno as d_deptno, e.deptno as e_deptno  
from dept d left outer join  emp e  
on d.deptno = e.deptno 
where e.deptno is null

这是因为on子句使用指定为条件的条件将行从一个表连接到另一个表-因此它将仅链接到具有空deptno且同时与dept记录匹配的deptno的emp记录.

由于这些条件是互斥的,因此查询将永远不会成功链接到emp记录,因此外部联接可确保为emp值返回空值.

在连接条件之后应用where子句-因此将is null条件移至where子句可确保仅选择没有匹配的emp记录的dept记录.

e_deptno为null在此查询中的on子句或where子句中均无效,因为e_deptno仅在select子句中定义(在应用了on,where和任何分组之后)-在having子句中可能有效(在MySQL中).

标签:outer-join,join,left-join,sql,mysql
来源: https://codeday.me/bug/20191123/2064749.html