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进行解答,不过效率都不如连接来得快,就不进行测试了。

posted @   Hider1214  阅读(461)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示