Leetcode: 相关子查询

时间:2021-09-06 12:14:26

Leetcode : Employees Earning More Than Their Managers

+—-+——-+——–+———–+
| Id | Name | Salary | ManagerId |
+—-+——-+——–+———–+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
+—-+——-+——–+———–+

Given the Employee table, write a SQL query that finds out employees who earn more than their managers.

思路:

做法一:对于每一个Employee,需要比较它的Salary和他的Manager的Salary,那么可以建一个表,每行既含有自己的Salary又含有Manager的Salary。用内连接建新表。

select Name from 
(
(select Id,Name,Salary,ManagerId from Employee) as a
inner join
(select ManagerId, Salary as ManagerSalary from Employee) as b
)
where a.Salary > b.ManagerSalary;

运行超时,可见内连接join的效率很低。

做法二:相关子查询,当我查询某行时,我需要去查询其ManagerId所对应的行。因此最直观的写法是这样的:

select Name
from Employee E1
where Salary >
(
select Salary from Employee E2 where E2.Id = E1.ManagerId
)

相关子查询中外查询和子查询对表各自重新命名为E1和E2,外查询每扫描一项,子查询必须要重新进行一次,因此这样写法的查询效率很低。

做法三:自连接。同一个表建两个别名。

select a.Name from Employee a, Employee b 
where a.ManagerId = b.Id and a.Salary > b.Salary;