子查询中的空值导致的问题。
例如有一张员工表, 表入面有自连接
现在要查询 不是经理的人员(就是manager_id 记录没有 他的employee_id的人员)
但是实际上找不到数据:
为什么呢
答案是自查询存在null值
而Not in 实际上就是 <>ALL 而用大于或小于来比较Null值的话,都返回null的。(false)
所以整体语句就返回Null了。
解决方法: 令自查询不存在Null值:
现在要查询 不是经理的人员(就是manager_id 记录没有 他的employee_id的人员)
上面的语句逻辑上看起来是没有错误的
SELECT emp.last_name
FROM
employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
from employees mgr);
但是实际上找不到数据:
为什么呢
答案是自查询存在null值
SELECT mgr.manager_id
from employees mgr
而Not in 实际上就是 <>ALL 而用大于或小于来比较Null值的话,都返回null的。(false)
所以整体语句就返回Null了。
解决方法: 令自查询不存在Null值:
SELECT emp.last_name
FROM
employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
from employees mgr
where not mgr.manager_id is null);