group by 和 order by 同時使用注意事項


寫sql的順序 :select -> from-> where->group by->having->order by.

解析器執行順序:from-> where->group by->having->select->order by.

一、不可取舉例

1、使用max()方法,雖然可以獲得最大值,但排序無效。
select id,seriesId,examId,paperId,employeeNo,MAX(score) as score,time,errorQueNum,state,createTime from ko_monthly_exam_history where seriesId = #{seriesId} and employeeNo = #{employeeNo} GROUP BY examId order by score DESC,time


2、子查詢:先order by -->再group by
對於簡單的排序可能有效,但實際使用中發現,該方式還是沒有得到期待值;

二、解決方法

 

select * from ko_monthly_exam_history
where id in(
select id from (
select SUBSTRING_INDEX(group_concat(id order by score DESC,time),',',1) as id
from `ko_monthly_exam_history` 
where seriesId = 2010008000010202
and employeeNo = 10024395 
group by examId
)t)

 

使用group_concat獲得分組的id,再使用SUBSTRING_INDEX截取id,最后使用in查詢獲取結果。

實際使用中需要測試查詢速度是否滿足項目應用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM