代码
# Write your MySQL query statement below
select
e1.name
from
Employee e1, Employee e2
where
e1.id = e2.managerId
Group by
e1.id, e1.name
Having
count(e2.id) >= 5
1. SELECT e1.name
- 我们最终想要的是经理的姓名。
- 这里的
e1代表“可能是经理”的员工。
2. FROM Employee e1, Employee e2
- 把
Employee表用了两次,分别起别名:e1:代表经理e2:代表普通员工(下属)
- 这种写法叫 自连接(self-join) —— 一张表和自己关联。
💡 为什么能这样?因为“经理”和“员工”其实都在同一张
Employee表里!
3. WHERE e1.id = e2.managerId
- 关键连接条件!
- 意思是:e1 的 id 等于 e2 的 managerId
- 也就是说:e1 是 e2 的经理
- 通过这个条件,我们就把“经理”和“他的下属”配对起来了。
select
e1.name as manager
,e2.name
,e2.department
,e2.managerId
from
Employee e1, Employee e2
where
e1.id = e2.managerId
| manager | name | department | managerId |
| ------- | ----- | ---------- | --------- |
| John | Dan | A | 101 |
| John | James | A | 101 |
| John | Amy | A | 101 |
| John | Anne | A | 101 |
| John | Ron | B | 101 |
4. GROUP BY e1.id, e1.name
- 现在我们要按经理分组,统计每个经理有多少个下属。
- 为什么同时
GROUP BY e1.id和e1.name?- 虽然
id是主键(唯一),但 SQL 标准要求:SELECT中非聚合字段必须出现在GROUP BY中。 - 所以为了安全兼容(尤其在 MySQL 严格模式下),同时写上
id和name。
- 虽然
5. HAVING COUNT(e2.id) >= 5
COUNT(e2.id):统计每个经理对应的下属数量(即 e2 有多少行)HAVING用于对分组后的结果进行筛选- 只保留那些下属数量 ≥ 5 的经理
结果
解题步骤:https://www.bilibili.com/video/BV1htfDBVEDw/

&spm=1001.2101.3001.5002&articleId=157651196&d=1&t=3&u=809f267f96624864baccdf3c7dfe0db2)
3772

被折叠的 条评论
为什么被折叠?



