能否问一个LeetCode上MySQL的简单问题?
来源:8-9 和堆相关的更多话题和广义队列

落叶灯花
2018-10-13
- 部门工资最高的员工
Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id。
±—±------±-------±-------------+
| Id | Name | Salary | DepartmentId |
±—±------±-------±-------------+
| 1 | Joe | 70000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
±—±------±-------±-------------+
Department 表包含公司所有部门的信息。
±—±---------+
| Id | Name |
±—±---------+
| 1 | IT |
| 2 | Sales |
±—±---------+
编写一个 SQL 查询,找出每个部门工资最高的员工。例如,根据上述给定的表格,Max 在 IT 部门有最高工资,Henry 在 Sales 部门有最高工资。
±-----------±---------±-------+
| Department | Employee | Salary |
±-----------±---------±-------+
| IT | Max | 90000 |
| Sales | Henry | 80000 |
±-----------±---------±-------+
我的解答:
select a.Department,b.Name as Employee, a.Salary from ((select b.name as Department ,max(a.Salary) as Salary from Employee a left join Department b on a.DepartmentId =b.Id group by b.name ) a left join Employee b on a.Salary=b.Salary);
执行结果是正确的,运行不通过,是怎么回事呢?
2回答
-
你的query有两个问题,
中间的select ((select b.name as Department ,max(a.Salary) as Salary from Employee a left join Department b on a.DepartmentId =b.Id group by b.name) a 应该使用join 而不是left join。
因为 如果department 表为空时 ,select 应该返回空, 如果使用left join 仍会返回employee表中的最大salary
第二个left join 应该是两个 约束条件, 薪水和departmentid ,如 (a.Salary=b.Salary and a.DepartmentID = b.DepartmentId)
--改写后: select a.Department, b.Name as Employee, a.Salary from ((select b.id as DepartmentID, b.name as Department, max(a.Salary) as Salary from Employee a join Department b on a.DepartmentId =b.Id group by b.name ) a left join Employee b on (a.Salary=b.Salary and a.DepartmentID = b.DepartmentId));
212019-01-05 -
liuyubobobo
2018-10-13
非常抱歉,MySQL相关的问题实在不是这个课程的主题。我也不是数据库的专家,没有研究过Leetcode上数据库相关的问题。
在这个课程的问答区,我可以回答所有Leetcode上的算法问题,毕竟这是一个算法与数据结构的课程。请谅解:)
加油!:)
00
相似问题