关于Oracle SQL中NOT IN子句的工作机制

时间:2018-04-22 18:01:09

标签: sql oracle subquery

以下是我的SQL查询的结果:

SELECT DISTINCT(department_id) 
from employees 
ORDER BY department_id;

结果:

DEPARTMENT_ID

       10
       20
       30
       40
       50
       60
       70
       80
       90
      100
      110

然后:

SELECT department_id 
FROM departments 
ORDER BY department_id;

DEPARTMENT_ID

       10
       20
       30
       40
       50
       60
       70
       80
       90
      100
      110
      120
      130
      140
      150
      160
      170
      180
      190
      200
      210
      220
      230
      240
      250
      260
      270

当我执行以下查询时,我得到结果:

SELECT department_id 
from departments  
where department_id IN (select distinct(department_id) from employees)  
ORDER BY department_id;

DEPARTMENT_ID

       10
       20
       30
       40
       50
       60
       70
       80
       90
      100
      110

但是,以下查询返回" NO Rows Selected"当我执行以下查询时:

SELECT department_id 
from departments  
WHERE department_id NOT IN (select distinct(department_id) from employees)   
ORDER BY department_id;

我所期望的是Employees表中不存在的部门的ID。 我觉得这是一个初学者的错误,但我无法解决这个问题。任何帮助都会受到很大的赞赏。

1 个答案:

答案 0 :(得分:3)

这是因为function clickRedirectHandler(event) { var attr = this.getAttribute("href"); // this === Clicked HTML element if (!window.confirm(attr)) { // Negate the confirm value, so if he click "cancel", it will evaluate as true event.preventDefault(); // Prevent the redirect } } function setRedirectConfirmationDialogs() { var links = document.getElementsByTagName('a'); for(var i = 0; i<links.length; i++){ links[i].addEventListener('click', redirectHandler); } } NULL department_id NOT employees is NULL`中至少有一个. When any value in the,根本没有返回任何行。

要解决此问题,我建议使用带有子查询的list is 始终

NOT EXISTS

(或者使用SELECT d.department_id FROM departments d WHERE NOT EXISTS (SELECT 1 FROM employees e WHERE d.department_id = e.department_id) ORDER BY d.department_id; / LEFT JOIN。)

可以使用子查询中的WHERE子句解决此问题。我认为最好使用一个符合你想要的结构。