我想排序我的結果,但我的順序聲明被忽略...我明白爲什麼,但不是如何解決它。這裏是我的代碼:MYSQL GROUP BY/ORDER BY confusion
SELECT
result.station_id as 'Station ID',
result.date as 'Date',
result.id as 'ID',
COALESCE(sum(if(result.parameter = '1', result.result, NULL)),'-') as 'RESULT A)',
COALESCE(sum(if(result.parameter = '2', result.result, NULL)),'-') as 'RESULT B)',
FROM (
SELECT
event.station_id,
event.date,
event.id,
e_result.result
FROM event
Inner Join e_result ON e_result.id = event.id
WHERE
(event.station_id = '0001') AND `devent`.`date` >= '1999-02-08' AND `event`.`date` <= '2011-12-20') as result
GROUP BY by result.id
ORDER BY
result.station_id ASC,
result.date DESC
這是正確的分組,但沒有排序結果後...似乎是整理分組。我需要的分組完成後排序的整個結果集(而不是每個分組)
輸出示例:
Station Date ID Result A Result B
20 7/6/2009 g003 - 3
12 2/8/1999 g000 19.2 -
12 2/8/1999 g001 19.9 -
12 2/14/1999 g002 19.1 -
17 4/9/2003 i001 22.2 4
應該
Station Date ID Result A Result B
12 2/14/1999 g002 19.1 -
12 2/8/1999 g000 19.2 -
12 2/8/1999 g001 19.9 -
17 4/9/2003 i001 22.2 4
20 7/6/2009 g003 - 3
表:
e_result id, parameter, result
g002, 1, 19.1
g000, 1, 19.2
g001, 1, 19.9
i001, 1, 22.2
i001, 2, 4
g003, 2, 3
event station_id, date, id
20, 7/16/2009, g003
12, 2/8/1999, g000
12, 2/8/1999, g001
12, 2/14/1999, g002
17, 4/9/2003, i001
向我們展示了一些輸出,你覺得是不正確排序。通常,在生成結果集後,最後會應用ORDER BY子句,因此不清楚你要問什麼。 – 2012-04-12 15:03:23
@MikeRyan我認爲他們希望在分組之前完成ORDER BY – Taryn 2012-04-12 15:12:40
這並不完全正確地回答你的問題,但可能會有所幫助 - 使用圖形查詢構建器將使在mysql中構建如此複雜的查詢變得容易很多而不會出錯。看看這篇文章在SO - http://stackoverflow.com/questions/2506610/visual-query-builder – 2012-04-12 15:14:52