美文网首页
LeetCode-SQL-收入超过经理的员工

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

作者: 皮皮大 | 来源:发表于2021-06-01 09:14 被阅读0次

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

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

image

题目

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

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

image

思路

思路1-自连接

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

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

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

image image

思路2-子连接

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

select
    e.Name as Employee
from Employee e
where Salary > (  -- 子连接
    select Salary 
    from Employee 
    where Id=e.ManagerId); 
image image

思路3-where条件过滤

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

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

相关文章

网友评论

      本文标题:LeetCode-SQL-收入超过经理的员工

      本文链接:https://www.haomeiwen.com/subject/unqwsltx.html