MySQL SELECT DISTINCT 多列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12188027/
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
MySQL SELECT DISTINCT multiple columns
提问by user765368
Let's say I have columns a, b c, d
in a table in a MySQL database. What I'm trying to do is to select the distinct values of ALL of these 4 columns in my table (only the distinct values). I tried stuff like:
假设我a, b c, d
在 MySQL 数据库的表中有列。我想要做的是在我的表中选择所有这 4 列的不同值(仅不同值)。我试过这样的东西:
SELECT DISTINCT a,b,c,d FROM my_table;
SELECT DISTINCT a,b,c,d FROM my_table GROUP BY a,b,c,d;
None of those worked. Can anybody help out here?
这些都没有用。有人可以帮忙吗?
Thank you
谢谢
NOTEI want the distinct values of the columns a, b, c d
separately. Not the distinct combination of values
注意我想要a, b, c d
单独的列的不同值。不是值的不同组合
采纳答案by Nesim Razon
can this help?
这有帮助吗?
select
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d
回答by Nicolas Castro
I know that the question is too old, anyway:
我知道这个问题太老了,无论如何:
select a, b from mytable group by a, b
will give your all the combinations.
会给你所有的组合。
回答by Adrian Cornish
Taking a guess at the results you want so maybe this is the query you want then
猜测你想要的结果,所以也许这就是你想要的查询
SELECT DISTINCT a FROM my_table
UNION
SELECT DISTINCT b FROM my_table
UNION
SELECT DISTINCT c FROM my_table
UNION
SELECT DISTINCT d FROM my_table
回答by Kelhen
Another simple way to do it is with concat()
另一种简单的方法是使用 concat()
SELECT DISTINCT(CONCAT(a,b)) AS cc FROM my_table GROUP BY (cc);
回答by T. Brian Jones
This will give DISTINCT values across all the columns:
这将在所有列中给出 DISTINCT 值:
SELECT DISTINCT value
FROM (
SELECT DISTINCT a AS value FROM my_table
UNION SELECT DISTINCT b AS value FROM my_table
UNION SELECT DISTINCT c AS value FROM my_table
) AS derived
回答by Hammad Khan
Both your queries are correct and should give you the right answer.
您的两个查询都是正确的,应该会给您正确的答案。
I would suggest the following query to troubleshoot your problem.
我建议使用以下查询来解决您的问题。
SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc
That is add count(*) field. This will give you idea how many rows were eliminated using the group command.
即添加 count(*) 字段。这将使您了解使用 group 命令消除了多少行。