astak16/blog-mysql

2 超过经理收入的员工

Opened this issue · 0 comments

题目

经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。查询收入超过他们经理的员工的姓名

create table employee (
	id int,
	name varchar(255),
	salary int,
	managerId int
);

insert into employee values 
(1, 'Joe', 70000, 3),
(2, 'Henry', 80000, 4),
(3, 'Sam', 60000, null),
(4, 'Max', 90000, null);

SQL

select employee.name from employee left join employee e
on employee.managerId = e.id
where employee.salary > e.salary;

解析

managerId 是经理 id ,同时经理也是员工,也就是说没有 managerId 是普通员工,有 managerId 的是经理。

所以将 employee 自连接,连接条件是 employee.managerId = e.id ,就可以把普通员工和经理连接起来了。

然后在筛选出 employee.salary > e.salary 的员工就行了。