Nick Maroulis
Nick Maroulis

Reputation: 487

Distinct on multiple columns in MySQL

I wish to find out the count of distinct rows in a MySQL DB.

id | val1 | val2 | val3

1  |  1   |  1   |  1
2  |  1   |  1   |  1
3  |  2   |  2   |  2
4  |  2   |  2   |  2

On the table above the query would return

val1 | val2 | val3 | count
1    |   1  |  1   |   2 
2    |   2  |  2   |   2

Does anyone know a reasonably efficient way of achieving this in MySQL.

Upvotes: 3

Views: 3494

Answers (1)

Himanshu
Himanshu

Reputation: 32602

You need to use GROUP BY clause for this:

SELECT val1, val2, val3, count(*) AS count
FROM mytable GROUP BY val1, val2, val3

See this fiddle

Upvotes: 5

Related Questions