1. 题目
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 |
+
2. 解法一
2.1 建表
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);
2.2 解答
考虑使用联结查询,下面是不断通过添加限制条件得到具体每一步的结果。
SELECT
*
FROM Employee AS a JOIN Employee AS b
;
+
| id | name | salary | managerId | id | name | salary | managerId |
+
| 4 | Max | 90000 | NULL | 1 | Joe | 70000 | 3 |
| 3 | Sam | 60000 | NULL | 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 | 1 | Joe | 70000 | 3 |
| 1 | Joe | 70000 | 3 | 1 | Joe | 70000 | 3 |
| 4 | Max | 90000 | NULL | 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL | 2 | Henry | 80000 | 4 |
| 2 | Henry | 80000 | 4 | 2 | Henry | 80000 | 4 |
| 1 | Joe | 70000 | 3 | 2 | Henry | 80000 | 4 |
| 4 | Max | 90000 | NULL | 3 | Sam | 60000 | NULL |
| 3 | Sam | 60000 | NULL | 3 | Sam | 60000 | NULL |
| 2 | Henry | 80000 | 4 | 3 | Sam | 60000 | NULL |
| 1 | Joe | 70000 | 3 | 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL | 4 | Max | 90000 | NULL |
| 3 | Sam | 60000 | NULL | 4 | Max | 90000 | NULL |
| 2 | Henry | 80000 | 4 | 4 | Max | 90000 | NULL |
| 1 | Joe | 70000 | 3 | 4 | Max | 90000 | NULL |
+
16 rows in set (0.00 sec)
SELECT
*
FROM Employee AS a JOIN Employee AS b
ON a.ManagerId = b.Id
AND a.Salary > b.Salary
;
+
| id | name | salary | managerId | id | name | salary | managerId |
+
| 1 | Joe | 70000 | 3 | 3 | Sam | 60000 | NULL |
+
1 row in set (0.00 sec)
SELECT
a.Name AS 'Employee'
FROM Employee AS a JOIN Employee AS b
ON a.ManagerId = b.Id
AND a.Salary > b.Salary
;
+
| Employee |
+
| Joe |
+
1 row in set (0.00 sec)
|