简体   繁体   中英

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

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.

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
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
 ...
HAVING hits > 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM