MYSQL按另一个表的计数过滤

时间:2011-07-21 22:07:46

标签: mysql sql database count

我正在接受MYSQL。 我有以下查询:

SELECT answers.data. * , COUNT( answers.reports.id ) AS rcount
FROM answers.data
LEFT JOIN answers.reports ON answers.data.id = answers.reports.answer_id
WHERE answers.data.question='4'
GROUP BY answers.data.id

它返回了我当前问题的所有答案,并添加了一个名为rcount(报告数量)的列

我希望它只返回少于3个报告的人。我尝试了以下代码:

SELECT answers.data. * , COUNT( answers.reports.id ) AS rcount
FROM answers.data
LEFT JOIN answers.reports ON answers.data.id = answers.reports.answer_id
WHERE answers.data.question='4' AND rcount < '3'
GROUP BY answers.data.id

但显然不是新情况发生的地方。因为我是新手,所以在手册中找不到解决方案。 感谢

1 个答案:

答案 0 :(得分:6)

使用HAVING子句:

SELECT answers.data.* , COUNT( answers.reports.id ) AS rcount
FROM answers.data
LEFT JOIN answers.reports ON answers.data.id = answers.reports.answer_id
WHERE answers.data.question='4'
GROUP BY answers.data.id
HAVING COUNT( answers.reports.id ) < 3