题目描述
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 |
+----------+
算法设计与分析:
- 这里不用使用distinct
方法一:打败27%
# Write your MySQL query statement below
SELECT
Name as Employee # 取别名,照应题意
FROM
Employee AS a # 取别名,为了方便使用
WHERE
Salary > (SELECT
Salary
FROM
Employee
WHERE
Id = a.Managerid)
方法二:使用where,打败99%
SELECT
a.Name AS 'Employee' # 起别名,我们只需要选出a的名字即可
FROM
Employee AS a,
Employee AS b # 会产生笛卡尔积
WHERE # 设置条件
a.ManagerId = b.Id
AND a.Salary > b.Salary
;
方法三:使用join,实际上, JOIN 是一个更常用也更有效的将表连起来的办法,我们使用 ON 来指明条件,打败88%
SELECT
a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
ON a.ManagerId = b.Id
AND a.Salary > b.Salary
;
**注:**法二、三参考自官方题解