Mysql – Limit distinct count of group by

group byMySQLperformance

Suppose for simplicity that I have a table t with columns id and value. I can find the ids that have more than one distinct value using a query such as

SELECT id, COUNT(DISTINCT(value)) AS count
FROM t
GROUP BY id
HAVING count > 1

Is there a more efficient way to do this? Can it be changed so that the count for each id stops as soon as more than one distinct value is found for it?

Best Answer

You can test this variation. In theory, it would use an (id, value) index to find the min and max and would not have to count the distinct values at all:

SELECT id
FROM t
GROUP BY id
HAVING MIN(value) < MAX(value) ;