Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Return fields where COUNT(*) is greater than

Tags:

database

mysql

I've got the following SQL, but I only want to return rows where 'hits' are greater than 10.

SELECT clicks.affiliate, COUNT(*) AS hits, affiliates.title, affiliates.url
FROM clicks
INNER JOIN affiliates ON affiliates.id = clicks.affiliate
GROUP BY clicks.affiliate

Thanks.

like image 858
Andre Backlund Avatar asked Oct 18 '10 14:10

Andre Backlund


2 Answers

To filter by an aggregate you need to use the having clause. Unlike many RDBMSs MySQL does allow you to use the column alias in this context (Most other RDBMSs would also insist on affiliates.title, affiliates.url being added to the group by clause as well)

SELECT clicks.affiliate, COUNT(*) AS hits, affiliates.title, affiliates.url
FROM clicks
INNER JOIN affiliates ON affiliates.id = clicks.affiliate
GROUP BY clicks.affiliate
HAVING hits > 10
like image 67
Martin Smith Avatar answered Oct 07 '22 17:10

Martin Smith


SELECT clicks.affiliate, COUNT(*) AS hits, affiliates.title, affiliates.url
FROM clicks
INNER JOIN affiliates ON affiliates.id = clicks.affiliate
GROUP BY clicks.affiliate
HAVING COUNT(*) > 10
like image 45
klaus Avatar answered Oct 07 '22 19:10

klaus