2014-02-10 192 views
1

記錄我有以下查詢工作正常:MySQL查詢使用COUNT()返回其中字段等於COUNT值

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 

如何修改第二個查詢以獲取這些記錄?

回答

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 
+1

非常感謝...這完全符合書面。 – IlludiumPu36

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 
+0

是啊,錯過順序位...看着你靈魂... – IlludiumPu36

+0

我有一個'as cnt'返回'未知列'attendance.cohort_fk'在'where子句'「的問題.... – IlludiumPu36