SELECT DISTINCT不同值的组合,加上非不同的值?

时间:2011-06-09 23:13:19

标签: mysql sql

我在查找有关执行简单MySQL查询的任何文档方面遇到了很多麻烦,该查询将从组合中返回所有不同的值,但也会返回另一个不同的列。

在我的情况下,report, topic, lat, lng, event必须是值的不同组合,但我还想返回docID列。

如果我将docID作为不同的值包含在内,则会返回每个文档,因为每个docID都是唯一的。

SELECT distinct report, topic, lat, lng, event, /*and each of their*/ docID FROM reports

我知道这个问题非常简单,但我找不到任何关于它的文档。

5 个答案:

答案 0 :(得分:4)

SELECT report, topic, lat, lng, event, 
group_concat(docID) as ids 
FROM reports
group by report, topic, lat, lng, event

答案 1 :(得分:1)

尝试使用GROUP BY:

SELECT report, topic, lat, lng, event, docID
FROM reports
GROUP BY report, topic, lat, lng, event

但请注意,如果某个特定分组中的docID重复,则只会显示一个值。

答案 2 :(得分:1)

逻辑可以给你答案。

如果多个文档具有(report,topic,lat,lng,event)的相同组合,那么您希望看到哪些docId?

如果你想要所有这些,那么你不需要真正的不同。

如果你只想要一个(或连接或任何操作),那么MySQL不能为你任意选择它,你必须查询它(MIN,MAX,FIRST,GROUP_CONCAT,......)。

然后回复是:您必须使用GROUP子句。喜欢:

SELECT report, topic, lat, lng, event, MIN(docId) AS docIdMin 
FROM my_table
GROUP BY report, topic, lat, lng, event

答案 3 :(得分:0)

select report, topic, lat, lng, event, max(docID)
From reports
group by report, topic, lat, lng, event

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_max

结帐

答案 4 :(得分:0)

我发现我使用分组和MaxMin来解决此问题,因为对于每条不同的行,可能会有多个DocId值。

SELECT report, topic, lat, lng, event, Max(docID) FROM reports
group by report, topic, lat, lng, event
相关问题