使用COUNT()进行MySQL查询以返回字段等于COUNT值的记录

时间:2014-02-10 07:24:18

标签: mysql

我有以下查询可以正常工作:

SELECT *, COUNT(*) FROM attendance, cohort 
WHERE 
attendance.cohort_fk = cohort.cohort_pk 
AND 
attendance.cohort_fk = '$cohort' 
AND 
YEAR(attendance.attended) = '$year'
GROUP BY attendance.person_id ASC

在表群组中,有一个int列'attendance_pass'。现在我想要另一个类似于上面的查询,它只返回COUNT(*) FROM attendance等于cohort.attendance_pass的记录。例如

SELECT *, COUNT(*) FROM attendance, cohort 
WHERE 
attendance.cohort_fk = cohort.cohort_pk 
AND 
attendance.cohort_fk = '$cohort' 
AND 
YEAR(attendance.attended) = '$year'
AND 
COUNT() = cohort.attendance_pass
GROUP BY attendance.person_id ASC

如何修改第二个查询以获取这些记录?

2 个答案:

答案 0 :(得分:1)

聚合函数必须在having子句中,而不是在where子句中。

顺便说一下,你可以使用别名。

我不认为你可以GROUP BY asc,你当然是指GROUP BY然后是ORDER BY ... ASC

select *, count(*) as cnt from attendance
-- etc.

where
--etc.
having cnt = cohort.attendance_pass
GROUP BY attendance.person_id
ORDER BY attendance.person_id ASC

答案 1 :(得分:1)

您需要使用HAVING

SELECT *, COUNT(*) FROM attendance, cohort 
WHERE 
attendance.cohort_fk = cohort.cohort_pk 
AND 
attendance.cohort_fk = '$cohort' 
AND 
YEAR(attendance.attended) = '$year'

GROUP BY attendance.person_id ASC

HAVING COUNT(*) = cohort.attendance_pass