1

我的员工表结构如下图所示

在此处输入图像描述

下面的查询根据部门平均最高工资获取部门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
)
4

2 回答 2

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
于 2013-05-18T07:37:43.490 回答
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

SQLFIDDLE

于 2013-05-18T07:41:35.910 回答