181. Employees Earning More Than Their Managers

Question

The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.

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

Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.

+----------+
| Employee |
+----------+
| Joe      |
+----------+

Thinking:

  • Method: 左外连接,速度比where要快。
# Write your MySQL 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
  • Method 2:通过查询确定判断条件,这种方法比较慢,经过两次查询,使用了两个session。
# Write your MySQL query statement below
select
    name as Employee
from
    Employee a
where
    a.Salary > (
        select
            b.Salary
        from
            Employee b
        where
            a.ManagerId = b.Id
    );

二刷

  1. 使用左外连接,这样我们可以合并两张表的内容。
  2. 使用where做出匹配。
    # Write your MySQL 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;
    
  3. 将同一张表使用两次做出匹配。
    # Write your MySQL query statement below
    SELECT a.Name as Employee
    FROM Employee a, Employee b
    where a.ManagerId = b.Id and a.Salary > b.Salary;