How to select the most recent set of dated records from a mysql table

后端 未结 7 1576
我在风中等你
我在风中等你 2020-11-29 01:00

I am storing the response to various rpc calls in a mysql table with the following fields:

Table: rpc_responses

timestamp   (date)
method      (varchar)
id          


        
相关标签:
7条回答
  • 2020-11-29 01:15

    Try this...

    SELECT o1.id, o1.timestamp, o1.method, o1.response   
    FROM rpc_responses o1
    WHERE o1.timestamp = ( SELECT max(o2.timestamp)
                           FROM rpc_responses o2
                           WHERE o1.id = o2.id )
    ORDER BY o1.timestamp, o1.method, o1.response
    

    ...it even works in Access!

    0 讨论(0)
  • 2020-11-29 01:15

    i used this,worked for me

    select max(timestamp),method,id from tables where 1 group by method,id order by timestamp desc 
    
    0 讨论(0)
  • 2020-11-29 01:19

    Self answered, but I'm not sure that it will be an efficient enough solution as the table grows:

    SELECT timestamp,method,id,response FROM rpc_responses 
    INNER JOIN
    (SELECT max(timestamp),method,id FROM rpc_responses GROUP BY method,id) latest
    USING (timestamp,method,id);
    
    0 讨论(0)
  • 2020-11-29 01:24

    Use this solution with caution:
    it is not guaranteed to work in future versions of mysql
    it is not known to work in mariadb 5.5

    This can query may perform well, because there are no joins.

    SELECT * FROM (
        SELECT timestamp, method, id, response
        FROM rpc_responses
        WHERE 1 # some where clause here
        ORDER BY timestamp DESC
    ) as t1
    GROUP BY method
    

    The "group by", collapses the result set on method, and returns only 1 row per method, the most recent one, because of the ORDER BY timestamp DESC in the inner query.

    FYI, PostgreSQL has a way of doing this built into the language:

    SELECT DISTINCT ON (method) timestamp, method, id, response
    FROM rpc_responses
    WHERE 1 # some where clause here
    ORDER BY method, timestamp DESC
    
    0 讨论(0)
  • 2020-11-29 01:26

    ...is more than one year later but i might help someone To select all the queries starting from latest

    SELECT *
    FROM rpc_responses
    ORDER BY timestamp DESC
    
    0 讨论(0)
  • 2020-11-29 01:27

    Subquery is very taxing when the data set becomes larger.

    Try this:

    SELECT t1.* 
    FROM rpc_responses AS t1 
    INNER JOIN rpc_responses AS t2 
    GROUP BY t1.method, t1.id, t1.timestamp
    HAVING t1.timestamp=MAX(t2.timestamp)    
    ORDER BY t1.timestamp, t1.method, t1.response;
    
    0 讨论(0)
提交回复
热议问题