找到至少有2名员工的部门

时间:2017-10-27 06:57:58

标签: mysql sql

我需要提出sql问题,该问题会显示所有部门中至少有2个人。

SELECT department.name
FROM department
INNER JOIN employee
ON department.id = employee.department_id
GROUP BY employee.id
HAVING COUNT(employee.id) >= 2;

它没有向我显示任何有关此查询的内容

2 个答案:

答案 0 :(得分:3)

我认为您在错误的列上使用GROUP BY 如果您想计算每个部门的员工,那么您需要GROUP BY department.id

SELECT department.id, department.name, COUNT(employee.id) AS total_employee
FROM department
INNER JOIN employee
ON department.id = employee.department_id
GROUP BY department.id, department.name
HAVING COUNT(employee.id) >= 2;

答案 1 :(得分:1)

试试这个:

SELECT d.name
FROM department d
WHERE
    (SELECT COUNT(*) FROM employee e
    WHERE d.id = e.department_id) >= 2

这样,如果您想更改限制(而不是2,另一个值),您的查询就会有效。

如果您愿意,可以使用INNER JOIN,将来所有没有员工的部门都不能使用它。