Employee
表包含所有員工,他們的經理也屬於員工。每個員工都有一個 Id,此外還有一列對應員工的經理的 Id。
+----+-------+--------+-----------+ | Id | Name | Salary | ManagerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | NULL | | 4 | Max | 90000 | NULL | +----+-------+--------+-----------+
給定 Employee
表,編寫一個 SQL 查詢,該查詢可以獲取收入超過他們經理的員工的姓名。在上面的表格中,Joe 是唯一一個收入超過他的經理的員工。
+----------+ | Employee | +----------+ | Joe | +----------+
答案:
select * FROM employee AS a, employee AS b where a.ManagerId = b.Id and a.Salary > b.Salary
拓展:選出有經理的員工即manageredId不為空
select Id from employee where ManagerId is not null
:當where中id對應有多個值的時候使用in 查出不為空的經理的薪水
select ManagerId from employee where Id in (select Id from employee where ManagerId is not null)