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

业务需求:需要实现分组排序并取组内状态优先级最高的数据。

示例:这里有一张这样的数据表,需求是根据error_type分组然后取status最小的第一条数据,如图:

写法一(无法实现):

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

猜你喜欢

转载自www.cnblogs.com/Jimc/p/12485225.html