Fork me on GitHub

leetcode-for-sql-收入超过经理的员工

LeetCode-181-超过经理收入的员工

大家好,我是Peter。本文讲解的是LeetCode-SQL的第181题目,难易程度:简单。

题目

Employee 表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。

1
2
3
4
5
6
7
8
+----+-------+--------+-----------+
| Id | Name | Salary | ManagerId |
+----+-------+--------+-----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
+----+-------+--------+-----------+

给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。

1
2
3
4
5
+----------+
| Employee |
+----------+
| Joe |
+----------+

题目利用如下的图形解释:Joe是员工,工资是70000,经理是编号3,也就是Sam,但是Sam工资只有60000

思路

思路1-自连接

下面提供自己的思路:通过给定表的自连接来实现查询

1
2
3
4
5
6
select
e1.Name as Employee
from Employee e1 -- 表的自连接
left join Employee e2
on e1.ManagerId = e2.Id -- 连接条件
where e1.Salary > e2.Salary

同样的代码运行两次,差别这么大!也不知道LeetCode是什么情况😭

思路2-子连接

通过给定表的子连接来实现,运行的速度比较慢。

1
2
3
4
5
6
7
select
e.Name as Employee
from Employee e
where Salary > ( -- 子连接
select Salary
from Employee
where Id=e.ManagerId);

思路3-where条件过滤

使用where语句来进行过滤;同时给次的表需要使用两次。运行速度挺快的

1
2
3
4
5
select
a.Name as Employee
from Employee as a,Employee as b -
where a.ManagerId = b.Id
and a.Salary > b.Salary;

本文标题:leetcode-for-sql-收入超过经理的员工

发布时间:2021年05月30日 - 16:05

原始链接:http://www.renpeter.cn/2021/05/30/leetcode-for-sql-%E6%94%B6%E5%85%A5%E8%B6%85%E8%BF%87%E7%BB%8F%E7%90%86%E7%9A%84%E5%91%98%E5%B7%A5.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea