2017-04-07 155 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