我的员工表结构如下图
以下查询根据部门平均最高薪水获得部门ID
SELECT dep_id
FROM employee
GROUP BY dep_id
ORDER BY AVG( salary ) DESC
LIMIT 1
输出
dep_id
2
但我在更新查询中有问题
UPDATE employee
SET salary = salary +1000
where dep_id = (
SELECT dep_id
FROM employee
GROUP BY dep_id
ORDER BY AVG( salary ) DESC
LIMIT 1
)
答案 0 :(得分:6)
您当前的SELECT
声明存在的问题是,它无法让多个dep_id
具有相同的最高平均salary
。我宁愿这样做以获得dep_id
,
SELECT dep_id
FROM employee
GROUP BY dep_id
HAVING AVG(salary) =
(
SELECT AVG(salary) avg_sal
FROM employee
GROUP BY dep_id
ORDER BY avg_sal DESC
LIMIT 1
)
然后,您现在可以为平均薪水最高的每个salary
更新emp_id
。
UPDATE employee a
INNER JOIN
(
SELECT dep_id
FROM employee
GROUP BY dep_id
HAVING AVG(salary) =
(
SELECT AVG(salary) avg_sal
FROM employee
GROUP BY dep_id
ORDER BY avg_sal DESC
LIMIT 1
)
) b ON a.dep_id = b.dep_id
SET a.salary = a.salary + 1000
答案 1 :(得分:3)
UPDATE employee e1
JOIN (SELECT dep_id, AVG(salary) avsal
FROM employee
GROUP BY dep_id
ORDER BY avsal DESC
LIMIT 1) e2
USING (dep_id)
SET e1.salary = e1.salary + 1000