mySQL 中的“In”运算符

问题描述 投票:0回答:1

员工:

| id  | name  | department | managerId |
+-----+-------+------------+-----------+
| 101 | John  | A          | null      |
| 102 | Dan   | A          | 101       |
| 103 | James | A          | 101       |
| 104 | Amy   | A          | 101       |
| 105 | Anne  | A          | 101       |
| 106 | Ron   | B          | 101       |
+-----+-------+------------+-----------|

从上面的 Employee 表中,我们需要管理至少 5 名员工的经理的姓名。 我想出了这个问题:

select name from employee where managerid in (
    select managerid 
    from employee 
    where managerid is not null 
    group by managerid having count(*) > 4
);

我期望以下输出:

| name |
+------+
| John |
+------+

但是,它却抛出了:

| ----- |
| Dan   |
| James |
| Amy   |
| Anne  |
| Ron   |

where子句返回的managerid为101。但是最终的select并没有选取相应的名称。这是哪里出了问题?

sql mysql where-clause
1个回答
0
投票

您正在选择经理拥有超过 4 名员工的所有员工。您需要更改 where 语句以按

id
而不是
managerid
进行过滤:

select name from employee where id in (
    select managerid 
    from employee 
    where managerid is not null 
    group by managerid having count(*) > 4
);
© www.soinside.com 2019 - 2024. All rights reserved.