MySQL 如何仅从一列中选择不同的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13848200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select distinct value from one column only
提问by user1810868
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:
当值不key
同时name
,我需要选择和key
。当我尝试:
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.
我得到了所有的行,因为查询对于列的组合是不同的:key
和name
。但是,我需要的只是不同的key
,我不在乎name
. 我有很多记录,所以我需要一个实用的方法。
回答by Justin
Query:
询问:
SELECT `key`, MAX(`name`) as name
FROM `table`
GROUP BY `key`
回答by fthiella
Why not just:
为什么不只是:
SELECT distinct key
FROM table
or
或者
SELECT key, name
FROM table
GROUP BY key
回答by systemboot
How about this:
这个怎么样:
select * from table group by key having count(key) = 1
回答by Bill Karwin
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.
这将为 的每个不同值返回一行key
,并且 的值name
是从该组中的行中任意选择的。在实践中,MySQL 倾向于从物理上首先存储在组中的行返回 name 的值,但这并不能保证。
As other answers show, you can put name into an aggregate expression.
正如其他答案所示,您可以将 name 放入聚合表达式中。
回答by amk
If you do not care about not groupped fields try this query -
如果您不关心未分组的字段,请尝试此查询 -
select key, name from table group by key order by name
MySQL lets selecting fields without using aggregate function.
MySQL 允许在不使用聚合函数的情况下选择字段。
order by namehelps to select first name from the group.
按名称排序有助于从组中选择名字。