I have records as follows:
key | name
--------------
1111 | aa
1111 | bb
2222 | cc
I need to select the key
and name
when the key
value is distinct. When I tried:
select distinct key, name from table;
I got all the rows since the query takes distinct for the combination of the columns: key
and name
. But, what I need is only distinct key
and I don't care about the name
. I have a lot of records, so I need a practical method.
Query:
SELECT `key`, MAX(`name`) as name
FROM `table`
GROUP BY `key`
Why not just:
SELECT distinct key
FROM table
or
SELECT key, name
FROM table
GROUP BY key
SELECT key, name FROM table GROUP BY key;
This returns one row for each distinct value of key
, and the value of name
is arbitrarily chosen from the rows in that group. In practice, MySQL tends to return the value of name from the row physically stored first in the group, but that's not guaranteed.
As other answers show, you can put name into an aggregate expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With