you can use
SELECT * FROM coupons GROUP BY merchantid LIMIT 0,5;
And it will work because
MySQL expands the use of GROUP BY so that the selection list can refer to non-aggregated columns not named in the GROUP BY clause ( see docs )
If you do not want MySQL to decide which merchantid to save, you can add your condition (in the example below - save the seller with the most clicks) using a subquery:
FIXED:
SELECT c1.* FROM coupons c1 JOIN ( SELECT t.merchantid, MAX(t.numberofclicks) maxnumberofclicks FROM coupons t GROUP BY t.merchantid ) c2 ON c1.merchantid = c2.merchantid AND c1.numberofclicks = c2.maxnumberofclicks LIMIT 0,5;
And another (more concise and probably faster on large datasets) way to trim the cat:
SELECT c1.* FROM coupons c1 JOIN coupons c2 ON c1.merchantid = c2.merchantid GROUP BY c1.merchantid, c1.numberofclicks HAVING c1.numberofclicks = MAX(c2.numberofclicks) LIMIT 0,5;
If you need 5 coupons with a maximum number of clicks, add ORDER BY c1.numberofclicks DESC to LIMIT 0,5 .
source share