写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查询获取结果。
实际使用中需要测试查询速度是否满足项目应用。