内部加入:这是一个最佳解决方案吗?

时间:2010-12-11 19:12:17

标签: sql inner-join

T1:员工[身份证,工资]

T2:部门[姓名,员工] (employeeid是T1的id的外键)

问题:编写查询以获取获得最高薪水的部门名称。

我的解决方案:

SELECT DISTINCT name
FROM department AS a
INNER JOIN employee AS b ON a.employeeid = b.id
AND b.salary
IN (    
    SELECT max( salary )
    FROM employee AS c
)

编辑:问题陈述是准确的,我们不是要找出薪水最高的员工。它说“......收到.....的部门”,而不是“......收到......的员工。”

这可以吗?或者这可以优化吗?

2 个答案:

答案 0 :(得分:3)

GROUP BY部门的名称和按SUM(工资)的顺序。

SELECT department.name
FROM department
JOIN employee ON department.employeeid = employee.id
GROUP BY department.name
ORDER BY SUM(salary) DESC
LIMIT 1

答案 1 :(得分:0)

怎么样:

SELECT employee.id, employee.salary, department.name
FROM department, employee 
where 
employee.id = department.employeeid and
employee.salary = (select max(salary) from employee)