MySQL MySQL根据一行的唯一性选择DISTINCT多列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10491474/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:17:13  来源:igfitidea点击:

MySQL Select DISTINCT multiple columns based on the uniqueness of one row?

mysql

提问by TK123

I'm trying to understand what this query does exactly:

我试图了解这个查询究竟做了什么:

SELECT DISTINCT `state`, `state_name` FROM `geo` ORDER BY `state_name` ASC

All I'm trying to do is select 2 columns (state and state_name), I want only unique rows that do not have duplicate values for the state field. I don't care if there are duplicate values in the state_name field.

我想要做的就是选择 2 列(state 和 state_name),我只想要状态字段没有重复值的唯一行。我不在乎 state_name 字段中是否有重复值。

Is my query checking both columns for uniqueness or just state?

我的查询是检查两列的唯一性还是仅检查状态?

回答by Chris Gessler

DISTINCT will return only distinct rows, so:

DISTINCT 将只返回不同的行,所以:

Is my query checking both columns for uniqueness or just state?

我的查询是检查两列的唯一性还是仅检查状态?

Both columns

两列

You could also switch to GROUP BY instead.

您也可以改用 GROUP BY。

SELECT `state`, `state_name` FROM `geo` group by 'state', 'state_name' ORDER BY `state_name` ASC 

回答by Shan Plourde

It's checking for unique combinations of state and state_name. Distinct operates on all columns included in your select list.

它正在检查 state 和 state_name 的唯一组合。Distinct 对选择列表中包含的所有列进行操作。

To only include unique state values, just select distinct state

要仅包含唯一的状态值,只需选择不同的状态