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

后端 未结 7 1624
我在风中等你
我在风中等你 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: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
    

提交回复
热议问题