我有以下查询,效果很好:
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
在表 cohort 中,有一个 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
如何修改第二个查询以仅获取这些记录?
最佳答案
你需要使用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
关于使用 COUNT() 的 MySQL 查询返回字段等于 COUNT 值的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21671243/