今天笔试做了一道简单算法题,一道简单 sql 题,sql 题的大意是分别有员工表和部门表两张表,关联字段是部门id,求每个部门薪资最高的员工的信息,薪资最高有多个人需要全部输出。
解法一
当时我只想到了一种解法
先用子查询查到每个部门的最高工资,然后把用部门id把员工表和部门表关联在一起,最后用部门的最高工资做筛选,完整 sql 如下
select d.name Department, e.name as Employee, e.salary as Salary
from Employee e left join Department d on e.departmentId = d.id
where (departmentId, salary) in (
select departmentId, max(salary)
from Employee
group by departmentId
);
解法二
后来看网上说还有以另一种解法,觉得也挺巧妙,学习了。整体思路跟解法一相同,只是把两个字段的 in 操作换成了一个字段,把父子查询的部门id放在子查询作为筛选条件
select d.name Department, e.name as Employee, e.salary as Salary
from Employee e left join Department d on e.departmentId = d.id
where salary in (
select max(salary)
from Employee emp
where e.departmentId = emp.departmentId
);
解法三
我根据解法一和解法二想到了一种新的解法,把员工表部门最高薪资子查询结果作为临时表,加入到员工表跟部门表的关联中,形成三表连接,最后用临时表跟员工表的薪资比较就能得到结果了
select d.name Department, e.name as Employee, e.salary as Salary
from Employee e
left join Department d on e.departmentId = d.id
left join (
select departmentId, max(salary) as max_salary
from Employee emp
group by emp.departmentId
) as temp
on temp.departmentId = e.departmentId
where e.salary >= temp.max_salary;
三种算法效率比较
理论上应该是解法一跟解法三的效率差不多,且他们的效率高于解法二。因为解法一和解法三,子查询都只需要执行一次,但是解法二,每行员工表记录都需要关联执行一次子查询,所以效率可能不如其他两个。
参考:sql—部门工资最高的员工
版权归原作者 Lucky小黄人 所有, 如有侵权,请联系我们删除。