MYSQL filter by count of another table
I'm beggining with MYSQL. I have the following query:
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
It's returning me all answers to the current question with an added column called rcount (number of reports)
I want it to return only those with less than 3 reports. I tried the following code:
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
but apr开发者_JAVA百科rently that's not where the new condition goes. I can't find in the manual a solution since I'm new to this. Thanks
Use a HAVING
clause:
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
精彩评论