SQL—day4
题目
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 |
+----------+
预备知识
①
sql99中语句执行顺序:
7 select 查询列表
1 from 表1 别名 【连接类型】
2 join 表2 别名
3 on 连接条件
4【where 筛选条件】
5【group by 分组】
6【having 分组后的筛选条件】
8【order by 排序列表】
9 limit 起始条目索引,条目数
②
where子句 : 需有条件地从表中选取数据
③
join函数:会在后续Blog中系统介绍
思路
1. ”和自己的xxx比” 这种问题基本都是自连接问题
2. 可以直接用join自连接、也可以用where筛选
3. 将子查询结果当作新表
代码
select a.Name as Employee
from Employee as a
join Employee as b
on a.ManagerID = b.ID
where a.Salary > b.Salary
SELECT a.Name AS Employee
FROM Employee as a,Employee as b
WHERE a.ManagerId=b.Id AND a.Salary>b.Salary;
select a.Name as Employee
from Employee as a,
(select Salary,Id from Employee) as b
where a.ManagerId=b.Id and a.Salary > b.Salary
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/employees-earning-more-than-their-managers