【LeetCode】mysql練習——超過經理收入的員工

Employee 表包含全部員工,他們的經理也屬於員工。每一個員工都有一個 Id,此外還有一列對應員工的經理的 Id。mysql

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

給定 Employee 表,編寫一個 SQL 查詢,該查詢能夠獲取收入超過他們經理的員工的姓名。在上面的表格中,Joe 是惟一一個收入超過他的經理的員工。sql

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

mysql腳本code

Create table If Not Exists Employee (Id int, Name varchar(255), Salary int, ManagerId int);
Truncate table Employee;
insert into Employee (Id, Name, Salary, ManagerId) values ('1', 'Joe', '70000', '3');
insert into Employee (Id, Name, Salary, ManagerId) values ('2', 'Henry', '80000', '4');
insert into Employee (Id, Name, Salary, ManagerId) values ('3', 'Sam', '60000', null);
insert into Employee (Id, Name, Salary, ManagerId) values ('4', 'Max', '90000', null);

本身先動動腦子ip

答案:leetcode

#本身寫的
SELECT
	e.`Name` Employee
FROM
	employee01 e
LEFT JOIN employee01 ep ON e.ManagerId = ep.Id
WHERE
	e.ManagerId IS NOT NULL
AND e.Salary > ep.Salary 

#答案
SELECT
	a. NAME AS Employee
FROM
	Employee01 AS a
JOIN Employee01 AS b ON a.ManagerId = b.Id
AND a.Salary > b.Salary

SELECT 
    a.name AS Employee
FROM employee01 AS a,employee01 AS b
where a.ManagerId = b.Id
AND a.Salary > b.Salary

題目來源:io

https://leetcode-cn.com/problems/employees-earning-more-than-their-managers/description/table

相關文章
相關標籤/搜索