选择既是经理又在经理手下工作的员工
Posted
技术标签:
【中文标题】选择既是经理又在经理手下工作的员工【英文标题】:Select employees, who are managers but also working under a manager 【发布时间】:2021-02-25 20:12:57 【问题描述】:我正在尝试构建一个查询来选择所有员工,他们是经理,但也在经理下工作。
例如在下表中
id | name | manager_id |
---|---|---|
1 | fresher | 2 |
2 | team lead | 3 |
3 | manager | null |
我只想获得团队负责人,作为我的选择查询的结果,我尝试使用以下查询,但出现错误。我也不确定这是否是正确的方法。
select e.id, e.name, m.name as mgr_name,
case when EXISTS (select 1 from emps where emps.manager_id = e.id) then 1
else 0 end as isMgr
from emps e
join emps m on e.mgr_id = m.id
where e.manager_id is not null and e.isMgr = 1
错误:
列名“isMgr”无效。
【问题讨论】:
@DaleK 更新了问题。 您不能在 where 子句中引用计算列,除非您将其包含在子查询中。否则你必须重复计算中使用的逻辑。 好的,除了使用子查询还有其他解决方案吗? 避免子查询怎么办?子查询很棒! 【参考方案1】:我只会使用exists
和过滤:
select e.*
from emps e
where e.manager_id is not null and
exists (select 1
from e e2
where e2.manager_id = e.id
);
【讨论】:
所以除了使用嵌套查询之外,没有其他解决方案。 @user1734269 。 . .您可以改用join
。这似乎是最简单的解决方案。以上是关于选择既是经理又在经理手下工作的员工的主要内容,如果未能解决你的问题,请参考以下文章