一、需要實現分組排序並且取組內狀態優先級最高的數據
有一張這樣的數據表, 需求是根據error_type分組然后取status最小的第一條數據
第一種寫法:
select t.* from ( select e.* from error_record e where e.status > 0 and e.error_type > 0 order by ) 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)