力扣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 |
+----------+
方法一:
使用 WHERE
语句
从两个表里使用 Select 语句可能会导致产生 笛卡尔乘积 。在这种情况下,输出会产生 4*4=16 个记录。然而我们只对雇员工资高于经理的人感兴趣。所以我们应该用 WHERE 语句加 2 个判断条件。
# Write your MySQL query statement below
select e1.name as Employee #选的是员工表的名字
from employee e1,#两表连接
employee e2
where e1.ManagerId=e2.Id and e1.salary>e2.salary;
#条件查询,e1是员工表,e2是经理表;首先是对应员工的经理;第二是对应员工的经理
方法 二:
使用 JOIN
语句
实际上, JOIN
是一个更常用也更有效的将表连起来的办法,我们使用 ON
来指明条件。
SELECT
a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
ON a.ManagerId = b.Id
AND a.Salary > b.Salary
;
作者:LeetCode
链接:https://leetcode-cn.com/problems/employees-earning-more-than-their-managers/solution/chao-guo-jing-li-shou-ru-de-yuan-gong-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。