我有以下sql:
SELECT `id` FROM `exchange` WHERE `photo` = 1 ORDER BY `id` DESC LIMIT 18
我怎样才能获得不同的location
值?
例如,执行此操作但会返回错误:
SELECT `id`, distinct(`location`) FROM `exchange` WHERE `photo` = 1 ORDER BY `id` DESC LIMIT 18
示例表:
id location
1 7
2 8
3 4
4 4
5 2
6 32
示例结果(当LIMIT 5时):
6,5,4,2,1
答案 0 :(得分:1)
DISTINCT
适用于整行,而不适用于每列的值。删除列ID
,您将拥有唯一的位置。
SELECT distinct `location`
FROM `exchange`
WHERE `photo` = 1
ORDER BY `id` DESC
LIMIT 18
更新1
您可以使用 AGGREGATE FUNCTION ,例如 MAX(),并按照ID
对它们进行分组。再试一次,
SELECT location, MAX(ID) ID
FROM exchange
GROUP BY location