当前位置:Gxlcms > 数据库问题 > MySQL实现分组排序并取组内第一条数据

MySQL实现分组排序并取组内第一条数据

时间:2021-07-01 10:21:17 帮助过:137人阅读

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)。

MySQL实现分组排序并取组内第一条数据

标签:code   优先级   排列   临时   font   info   固定   HERE   alt   

人气教程排行