zoukankan      html  css  js  c++  java
  • 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)。

  • 相关阅读:
    linux bash shell之declare
    shell中的特殊符号
    工作常用shell集合
    sed实例收集
    vim粘贴代码时缩进混乱
    使用脚本实现killproc的功能
    zabbix 的安装
    Linux SSH 互信
    CeontOS7安装ansible
    xtrabackup 链接不上MySQL的问题
  • 原文地址:https://www.cnblogs.com/Jimc/p/12485225.html
Copyright © 2011-2022 走看看