gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:40:51 25 4
gpt4 key购买 nike

我有以下查询,效果很好:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com