LeetCode:181.超过经理收入的员工

题目链接:https://leetcode-cn.com/problems/employees-earning-more-than-their-managers/

题目

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 |
+----------+

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/employees-earning-more-than-their-managers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解答

第一想法,通过自连接,再做减法。

---- oracle ----
/* Write your PL/SQL query statement below */
select c.Name as Employee
from
(
    select a.Name,
           (a.Salary - b.Salary) as Salary
    from Employee a
    left join Employee b
    on a.ManagerID = b.Id
) c
where c.Salary > 0 ---- 868ms

应该可以继续优化的。。

---- oracle ----
/* Write your PL/SQL query statement below */
select a.Name as Employee
from Employee a
left join Employee b
on a.ManagerID = b.Id
where a.Salary > b.Salary ---- 528ms

通过where实现

---- MySQL ----
select a.Name as Employee
from Employee a,
     Employee b
where a.ManagerId = b.Id
and a.Salary > b.Salary;  ---- 260ms

思考

内连接会自动过滤null,所以关联的时候无须再设定ManagerId is not null过滤条件。

子查询性能 & 关联查询,到底哪个快?验证一番。

直接通过from table a, table b会产生笛卡尔积,影响效率。

另外,还可通过子查询和exists进行解答,不过效率都不如连接来得快,就不进行测试了。

猜你喜欢

转载自www.cnblogs.com/hider/p/11723669.html