業務需求:需要實現分組排序並取組內狀態優先級最高的數據。
示例:這里有一張這樣的數據表,需求是根據error_type分組然后取status最小的第一條數據,如圖:

寫法一(無法實現):
select t.* from ( select e.* from error_record e where e.status > 0 and e.error_type > 0 order by e.status ) t group by t.error_type
查詢結果

這種寫法無法實現我們的需求, 原因是MySQL分組查詢時默認按照id從小到大的順序排列讓我們自定義的排序失效了。
寫法二(可實現):
select t.* from ( select e.* from error_record e where e.status > 0 and e.error_type > 0 order by e.status limit 1000 ) t group by t.error_type
查詢結果

這種寫法可以實現我們的需求, 在臨時表內部排序時用limit字段固定排序, 然后在臨時表外分組就可以改變group by默認排序的問題(注: 原表中error_typ為3的數據只有一條就是status: 2)。
