【问题标题】:group by follow by order by in mysql在mysql中按顺序分组
【发布时间】:2017-04-07 06:11:10
【问题描述】:

我想找出哪个group by后面跟order by的查询。

我的表是 resource_monitor

id  |   server_ip   |    rdp_connection
1   |  192.168.1.45 |          9
2   |  192.168.1.46 |          12
3   |  192.168.1.45 |          8
4   |  192.168.1.45 |          4
5   |  192.168.1.46 |          3

我有用户查询

select * from resource_monitor group by server_ip order by id desc

这给了我结果

id  |   server_ip   |    rdp_connection
2   |  192.168.1.46 |          12
1   |  192.168.1.45 |          9

但我想要所有唯一 server_ip 的最后一条记录

id  |   server_ip   |    rdp_connection
4   |  192.168.1.45 |          4
5   |  192.168.1.46 |          3

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您可以按照以下方式使用子查询

    SELECT *
        FROM
          (SELECT *
           FROM resource_monitor
           ORDER BY id DESC) AS test
        GROUP BY test.server_ip
    

    【讨论】:

      【解决方案2】:

      您需要使用子查询获取第一个 max(id) 并在 where 子句中使用它

       select * from resource_monitor where id in 
            (select max(id) from resource_monitor group by server_ip ) 
          order by id desc
      

      【讨论】:

        【解决方案3】:

        看着你的数据样本,你似乎需要每个 server_ip 的最后一个值

        select id, server_ip, rdp_connection
        from resource_monitor
        where ( id,server_ip ) in 
        ( select max(id) as id, server_ip from resource_monitor 
          group by server_ip )
          order by id desc
        

        【讨论】:

          猜你喜欢
          • 2011-06-08
          • 2020-11-21
          • 1970-01-01
          • 1970-01-01
          • 2017-03-29
          • 1970-01-01
          • 1970-01-01
          • 2022-01-04
          • 1970-01-01
          相关资源
          最近更新 更多