-- checked on 4M rows
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`company` int(11) NOT NULL,
`customer` int(11) NOT NULL,
`item` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `search` (`company`,`customer`,`item`)
) ENGINE=MyISAM AUTO_INCREMENT=4000001 DEFAULT CHARSET=utf8;
-- 1) ~ 2.2sec
SELECT company, count(customer) as `customers_count`
FROM (SELECT customer, company FROM test GROUP BY customer HAVING COUNT(DISTINCT item) > 5) as `temp`
GROUP BY company
ORDER BY customers_count DESC
LIMIT 100
-- 2) ~2.2sec
SET @rank = 0;
SELECT rank, company FROM (
SELECT @rank := @rank + 1 as `rank`, company FROM (
SELECT company, count(customer) as `customers_count`
FROM (SELECT customer, company FROM test GROUP BY customer HAVING COUNT(DISTINCT item) > 5) as `temp`
GROUP BY company
ORDER BY customers_count DESC
LIMIT 100
) as `temp2`
) as `temp3`
WHERE company = 159