这个SQL查询有什么问题

时间:2015-01-12 13:11:48

标签: php mysql sql

我需要找到这个SQL有什么不好的地方:

SELECT DepartmentName, COUNT(*) 
FROM employee,department 
WHERE employee.DepartmentID = department.DepartmentID 
GROUP BY DepartmentName
WHERE COUNT(*)>1

我认为COUNT(*)中的问题是因为它返回了所有行的计数。那么我怎么认为属性sql将没有where语句。帮帮我,我不擅长SQL。

2 个答案:

答案 0 :(得分:6)

您必须使用having子句而不是声明末尾的位置:

SELECT DepartmentName, COUNT(*) 
FROM employee,department 
WHERE employee.DepartmentID = department.DepartmentID 
GROUP BY DepartmentName
having COUNT(*)>1

答案 1 :(得分:5)

SELECT DepartmentName, COUNT(*) AS count
FROM employee,department 
WHERE employee.DepartmentID = department.DepartmentID 
GROUP BY DepartmentName
HAVING count>1;