LeetCode: 181 more than the manager income employees.

Topic links: https://leetcode-cn.com/problems/employees-earning-more-than-their-managers/

topic

Employee table contains all employees, their managers belong to employees. Each employee has a Id, in addition to a correspondence Id manager of staff.

---- + ------- + -------- + + ----------- +
| Id | the Name | the 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 you can get the names of managers earning more than their employees. In the above table, Joe is the only one earning more than his manager's staff.

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

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/employees-earning-more-than-their-managers
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

answer

The first idea, since the connection, do the subtraction.

---- oracle ----
/* Write your PL/SQL query statement below */
select c.Name as Employee
from
(
    select a.Name,
           (a.Salary - b.Salary) as Salary
    from Employee a
    left join Employee b
    on a.ManagerID = b.Id
) c
where c.Salary > 0 ---- 868ms

You should be able to continue optimization. .

---- oracle ----
/* Write your PL/SQL 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 ---- 528ms

By whererealization

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

Think

The connection will automatically filter null, no longer so when the associated set ManagerId is not nullfilters.

Subqueries Performance & related inquiries, which in the end fast? Some verification.

Directly through from table a, table bit will produce a Cartesian product, affect efficiency.

In addition, also by sub-queries and existstheir answers, but not as efficient connection comes and will not be tested.

Guess you like

Origin www.cnblogs.com/hider/p/11723669.html