• 首页
  • 发布文章
  • 我的文章
  • 我的收藏
  • 设置
  • 退出

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

咔咔咔 2021-11-12 17:21:38
收藏
编辑
上架
下架

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

**示例:**这里有一张这样的数据表,需求是根据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)。

本文转自 https://www.cnblogs.com/Jimc/p/12485225.html,如有侵权,请联系删除。