Strong deduction 181. Employees who exceed manager's income
https://leetcode-cn.com/problems/employees-earning-more-than-their-managers/
The Employee table contains all employees, and their managers are also employees. Each employee has an Id, and there is also a list of Ids corresponding to the employee's manager.
+ ---- + ------- + -------- + ----------- +
| Id | Name | Salary | ManagerId |
+ ---- + ------- + -------- + ----------- +
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 60000 | NULL |
| 4 | Max | 90000 | NULL |
+ ---- + ------- + -------- + ----------- +
Given the Employee table, write a SQL query that can get the names of employees whose income exceeds their managers. In the table above, Joe is the only employee whose income exceeds his manager.
+----------+
| Employee |
+----------+
| Joe |
+----------+
method one:
Use WHERE
statement
Use the Select statement from two tables could result in a Cartesian product . In this case, the output will produce 4 * 4 = 16 records. However, we are only interested in people whose wages are higher than their managers. So we should add two judgment conditions with WHERE statement.
# 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是经理表;首先是对应员工的经理;第二是对应员工的经理
Method Two:
Use JOIN
statement
In fact, it JOIN
is a more common and more effective way to connect tables, we use ON
to specify the conditions.
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。