A slightly modified request from this article on my blog:
SELECT l.* FROM ( SELECT category, COALESCE( ( SELECT count FROM mytable li WHERE li.category = dlo.category ORDER BY li.category DESC, li.count DESC, li.id DESC LIMIT 9, 1 ), CAST(-1 AS DECIMAL)) AS mcount COALESCE( ( SELECT id FROM mytable li WHERE li.category = dlo.category ORDER BY li.category DESC, li.count DESC, li.id DESC LIMIT 9, 1 ), CAST(-1 AS DECIMAL)) AS mid FROM ( SELECT DISTINCT category FROM mytable dl ) dlo ) lo, mytable l WHERE l.category >= lo.category AND l.category <= lo.category AND (l.count, l.id) >= (lo.mcout, lo.id)
You need to create a composite index on (category, count, id) so that it works efficiently.
Note the use of l.category >= lo.category AND l.category <= lo.category instead of simple: l.category = lo.category
This hack to make MySQL efficient Range check for each record
source share