Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select distinct value from one column only

Tags:

mysql

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.

like image 896
user1810868 Avatar asked Dec 12 '12 20:12

user1810868


3 Answers

Query:

SELECT `key`, MAX(`name`) as name
FROM `table`
GROUP BY `key`
like image 176
Justin Avatar answered Nov 16 '22 19:11

Justin


Why not just:

SELECT distinct key
FROM table

or

SELECT key, name
FROM table
GROUP BY key
like image 31
fthiella Avatar answered Nov 16 '22 17:11

fthiella


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.

like image 1
Bill Karwin Avatar answered Nov 16 '22 18:11

Bill Karwin