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