2017-03-06 55 views
0

我有日誌「SNMP陷阱思科口」一表:如何由兩個參數選擇最後一條記錄?

mysql> select id, ip, `index`, trap_date from cisco_trap order by id desc limit 20; 

id  ip   index trap_date   
61110 1582065982  6 2017-03-06 10:27:07 
61109 1582065982  6 2017-03-06 10:21:58 
61108 175141121  45 2017-03-05 22:40:58 
61107 175141121  45 2017-03-05 22:40:52 
61106 175141121  45 2017-03-05 22:39:21 
61105 175141121  45 2017-03-05 22:20:18 
61104 175141121  45 2017-03-05 22:17:56 
61103 175141121  45 2017-03-05 22:17:50 
61102 1582065982  16 2017-03-03 17:00:33 
61101 1582065982  6 2017-03-03 17:00:36 
61100 1582065982  6 2017-03-03 16:42:47 
61099 1582065982  16 2017-03-03 15:29:55 
61098 1582065982  6 2017-03-03 15:30:03 
61097 1582065982  16 2017-03-03 15:27:28 
61096 1582065982  6 2017-03-03 15:27:23 
61095 1582065982  6 2017-03-03 15:26:27 
61094 1582065982  16 2017-03-03 15:26:21 
61093 1582065982  16 2017-03-03 15:25:58 
61092 1582065982  6 2017-03-03 15:25:52 
61091 1582065982  6 2017-03-03 15:23:51 

IP是知識產權在INET_NTOA和index是思科的端口號。 如何選擇由每個端口(index)每個IP最後一個記錄(日誌)?

+0

退房GROUP BY。 – jarlh

回答

0

您可以使用MAXGROUP BY

SELECT * from cisco_trap 
JOIN (
    select ip, `index`, max(trap_date) as max_date 
    from cisco_trap 
    group by ip, `index` 
) t 
ON t.ip = cisco_trap.ip 
AND t.`index` = cisco_trap.`index` 
AND t.max_date = cisco_trap.trap_date 
+0

查詢運行速度非常慢( – Vadym

+0

@Vadym查詢速度將取決於數據庫中的表中的記錄數。如果你能在trap_date'的'特定的持續時間可能會在加快幫助添加一個'WHERE'條款和限制查詢查詢。 –

0

有獲得此做了兩個方法:

  1. 這使100%準確的結果。但會減慢。

    SELECT id, 
        ip, 
        `index`, 
        trap_date 
    FROM cisco_trap 
    WHERE id IN ( 
          SELECT max(id) 
          FROM cisco_trap 
          GROUP BY ip, index 
         ) 
    ORDER BY id DESC 
    LIMIT 20 
    

2,因爲我有時間研究100。人說用這個,因爲它是那麼上面的查詢速度更快,但對我來說這個查詢沒有提供準確的結果。所以儘量1

SELECT id, ip, `index`, trap_date 
FROM ( 
     SELECT * 
     FROM cisco_trap 
     ORDER BY id DESC , 
       index DESC, 
       id DESC 
    ) 
GROUP BY ip , index 
limit 20; 
相關問題