如何通过两个参数选择最后一条记录?

时间:2017-03-06 10:10:02

标签: mysql sql

我有一个日志'snmp trap cisco port'的表:

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中的ip,index是cisco端口号。 如何选择每个端口(index)每个ip的最后一条记录(日志)?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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. 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;