SELECT pnumber, pname, COUNT(*)
FROM project
INNER JOIN works_on ON pno=pnumber
INNER JOIN department ON dnumber=dnum
GROUP BY pnumber
现在,mysql将返回项目编号和名称,以及正在处理它的员工数量。我想要做的是mysql只计算来自部门5的员工。换句话说,有来自不同部门的人员从事项目工作,但我只想要部门5的人员计算,而不是全部。
答案 0 :(得分:2)
您可以使用WHERE
SELECT pnumber, pname, COUNT(*)
FROM project
JOIN works_on ON pno = pnumber
JOIN department ON dnumber=dnum
WHERE dnumber = 5
GROUP BY pnumber
修改强>
SELECT pnumber, pname, COUNT(*),SUM(IF(dnumber=5, 1, 0)) AS count5
FROM project
JOIN works_on ON pno = pnumber
JOIN department ON dnumber=dnum
GROUP BY pnumber
答案 1 :(得分:2)
如果Barmar和Shafeeq建议使用WHERE
条款对您不起作用(例如,如果您需要在结果中包含所有部门,但只计算部门5中的人员),您可以使用此:
SUM(IF(dnum=5, 1, 0)) AS CountFromDepartment5
所以我们有:
SELECT pnumber, pname, COUNT(*) AS TotalCount, SUM(IF(dnum=5, 1, 0)) AS CountFromDepartment5
FROM project
INNER JOIN works_on ON pno=pnumber
INNER JOIN department ON dnumber=dnum
GROUP BY pnumber
答案 2 :(得分:0)
使用指定所需部门的WHERE
子句。
SELECT pnumber, pname, COUNT(*)
FROM project
INNER JOIN works_on ON pno=pnumber
WHERE dnumber = 5
GROUP BY pnumber
您不需要加入department
,因为部门编号也作为works_on
表中的外键存在。