2017-04-07 245 views
2

我想知道查询在哪个group by后跟order by。group by by by by mysql

我的表是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组由SERVER_IP顺序按id降序

这给我造成的

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 

回答

1

你可以用子查询确实需要使用,如下

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

你需要使用子查询来获取第一最大值(ID),并在where子句

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

望着你的数据样本似乎你需要的最后一个值对每个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