头图

This question uses MySQL 8.0 and has not been tested in MySQL 5.6, so it is not guaranteed to be correct.

topic

Topic source: income exceeds the manager's income 161e8d7428b13b

Managers are also employees. Each employee has an Id, in addition to a column of Id corresponding to the employee's manager. Look up the names of employees who earn more than their managers

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;

Parse

managerId is the manager id , and the manager is also an employee, that is to say, no managerId is an ordinary employee, and managerId is a manager.

Therefore, employee self-connected, and the connection condition is employee.managerId = e.id , and ordinary employees and managers can be connected.

Then filter out the employees employee.salary > e.salary

More reference for solving problems: https://github.com/astak16/blog-mysql


uccs
759 声望91 粉丝

3年 gis 开发,wx:ttxbg210604