【问题标题】:Finding employees who are not managers寻找不是经理的员工
【发布时间】:2019-03-01 22:48:21
【问题描述】:

我有一张桌子,里面有 staff_id 和 manager_id。附上截图。

我使用这个查询找到了经理:

select e.first_name as employee , m.first_name as manager
from sales.staffs E
inner JOIN sales.staffs M ON M.staff_id = E.manager_id

如何提取非经理员工的列表?

我的示例表

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    你可以这样做:

    select * from sales.staff 
    where staff_id not in (select manager_id from sales.staff)
    

    【讨论】:

    • 我试过你提到的查询。它不返回任何行。但是,如果我尝试 SELECT * FROM sales.staffs A WHERE A.staff_id not in (SELECT DISTINCT sales.staffs.manager_id FROM sales.staffs WHERE sales.staffs.manager_id IS NOT NULL) 它可以工作。我想知道为什么?
    • 根据您的数据,它应该显示:3、4、6、8、9 和 10,因为这些值不会显示在 manager_id 列中。
    【解决方案2】:

    使用不存在

    select t1.* from from sales.staff t1
             where not exists ( select 1 from sales.staff t2 where t1.staff_id=t2.manager_id )
    

    如果您使用not in,则使用null chechk

    select t.* from sales.staff  t 
    where t.staff_id not in (select manager_id from sales.staff where manager_id IS NOT NULL)
    

    【讨论】:

      【解决方案3】:

      我猜经理的所有 id 都存储在 manager_id 列中。
      此外,如果 manager_id 列是 null,那么该员工也是经理(?)。
      所以要得到所有你应该做的经理:

      select * from sales.staffs 
      where 
        manager_id is null
        or
        staff_id in (select distinct manager_id from sales.staffs)
      

      现在要让不是经理的员工,您只需否定条件:

      select * from sales.staffs 
      where 
        manager_id is not null
        and
        staff_id not in (select distinct manager_id from sales.staffs)
      

      【讨论】:

      • 感谢您的回复。欣赏它。对于不是经理的员工,我必须稍微改变一下才能获得结果为 . select * from sales.staffs where manager_id is not null and staff_id not in(从 sales.staffs 中选择不同的 manager_id WHERE sales.staffs.manager_id IS NOT NULL)
      • @mgr810 distinct 拒绝任何空值,因此您不需要 `WHERE sales.staffs.manager_id IS NOT NULL`,如上面的代码
      【解决方案4】:

      作为@The Impalers 正确答案的扩展,您的查询将变为:

      select e.first_name as employee , m.first_name as manager
      from sales.staffs E
      inner JOIN sales.staffs M ON M.staff_id = E.manager_id
      WHERE m.manager_id IS NULL
      

      由于您想要一个非经理人员的列表,您可以使用此解决方案,它将检查 manager_id 是否等于 NULL(假设这意味着没有经理)。

      另一种解决方案是基于 NOT EXIST 进行 LEFT JOIN,这将过滤您的表并显着缩短您的获取时间。

      【讨论】:

      • 你不会在INNER JOIN 上获得NULL 值,请改用LEFT JOIN
      • @WEI_DBA 哎呀!你是对的,改变了我的文字:)
      • 感谢您的回复。欣赏它。
      猜你喜欢
      • 1970-01-01
      • 2020-03-12
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多