【问题标题】:Finding an ID not in another column查找不在另一列中的 ID
【发布时间】:2019-10-16 20:25:42
【问题描述】:

我正在做一个小的 SQL 练习,并且正在为这个问题挠头。

我正在尝试查找没有其他员工向其报告的所有员工。 这是employees 表的样子:

   EmployeeId   LastName    FirstName   Title                 ReportsTo
             1  Adams       Andrew      General Manager       null
             2  Edwards     Nancy       Sales Manager         1
             3  Peacock     Jane        Sales Support Agent   2
             4  Park        Margaret    Sales Support Agent   2
             5  Johnson     Steve       Sales Support Agent   2
             6  Mitchell    Michael     IT Manager            1
             7  King        Robert      IT Staff              6
             8  Callahan    Laura       IT Staff              6

我认为其中一个简单的查询就可以做到:

SELECT *
FROM employees
Where EmployeeId not in (select ReportsTo from employees)


SELECT *
FROM employees
Where EmployeeId not in (ReportsTo)

但是那些返回以下结果,这不是我想要的:

EmployeeId  LastName    FirstName   Title                ReportsTo
         2  Edwards     Nancy       Sales Manager        1
         3  Peacock     Jane        Sales Support Agent  2
         4  Park        Margaret    Sales Support Agent  2
         5  Johnson     Steve       Sales Support Agent  2
         6  Mitchell    Michael     IT Manager           1
         7  King        Robert      IT Staff             6
         8  Callahan    Laura       IT Staff             6

为什么NOT IN 返回的项目肯定在该列中?如果我错误地使用了NOT IN,我将如何退回不在ReportsTo 中的物品?

【问题讨论】:

  • 第一个查询应该返回一个空的结果集。请改用NOT EXISTS
  • 指定您要查找的结果。

标签: sql sqlite join


【解决方案1】:

not exists 与相关子查询一起使用(如 jarlh 所述):

select *
from employees e
where not exists (
    select 1
    from employees e1 
    where e1.ReportsTo = e.EmployeeId   
)

【讨论】:

  • @ksm 。 . . not exists 是使用子查询时的最佳实践; not inNULL 值有意外行为。不要使用它。别担心。
  • @GordonLinoff(和 GBM)啊!有道理,谢谢!
【解决方案2】:

您的第一个查询的问题是您将 NOT IN 与包含 NULL 值的列表一起使用。
所以比较 EmployeeId 就像说 5:

5 NOT IN (null, 1, 2, 6)

将返回NULL,因为与NULL 的任何比较都会返回NULL,并且EmployeeId 不会包含在结果中。
改为:

SELECT *
FROM employees
Where EmployeeId not in (
  select ReportsTo 
  from employees 
  where ReportsTo is not null
);

请参阅demo
结果:

| EmployeeId | LastName | FirstName | Title               | ReportsTo |
| ---------- | -------- | --------- | ------------------- | --------- |
| 3          | Peacock  | Jane      | Sales Support Agent | 2         |
| 4          | Park     | Margaret  | Sales Support Agent | 2         |
| 5          | Johnson  | Steve     | Sales Support Agent | 2         |
| 7          | King     | Robert    | IT Staff            | 6         |
| 8          | Callahan | Laura     | IT Staff            | 6         |

【讨论】:

    【解决方案3】:

    您可以简单地使用以下查询--

    select * from employees emp where employeeID not in (select ReportsTo from employee)
    

    【讨论】:

    • 这...几乎是我帖子中的确切查询?
    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 2018-05-30
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多