我有一个sql查询,该查询输出各个部门中最低工资的员工。它通过找到每个部门的最低工资,并找到薪水与任何部门都匹配的人员来做到这一点。在这种情况下,人员1可以属于部门A,薪水为70k(即使她部门的最低工资为45k),如果另一个部门的最低工资为70k,则在查询中返回该人员。但是,如果我要输出其所属部门的最低工资的人员的姓名怎么办(这样一来,将不再返回1号人员)。这是当前的sql查询:
$resourceClass = 'App\Entity\User\User'
答案 0 :(得分:1)
如果您具有MySQL 8.0,那么最简单的方法是使用窗口函数:
SELECT *
FROM (SELECT *, RANK() OVER(PARTITION BY department_id ORDER BY salary DESC) AS r
FROM tab) sub
WHERE r = 1;
或者:
SELECT first_name, last_name, salary, department_id
FROM employees e
WHERE (department_id,salary) IN
( SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id);
答案 1 :(得分:1)
代替IN子句,您还可以使用内部联接
SELECT first_name, last_name, salary, department_id
FROM employees
INNER JOIN ( SELECT department_id, MIN(salary) min_sal
FROM employees
GROUP BY department_id
) t on t.department_id =employees.department_id
and employees.salary = t.min_sal;
这应该对性能更好