mysql - 如何从 mysql 表中选择最新的日期记录集

标签 mysql sql date greatest-n-per-group

我将各种 rpc 调用的响应存储在一个 mysql 表中,其中包含以下字段:

Table: rpc_responses

timestamp   (date)
method      (varchar)
id          (varchar)
response    (mediumtext)

PRIMARY KEY(timestamp,method,id)

methodid 的所有现有组合选择最新响应的最佳方法是什么?

  • 对于给定的方法/ID,每个日期只能有一个响应。

  • 并非所有调用组合都必须在给定日期出现。

  • 有几十种方法、数千个id和至少365个不同的日期

样本数据:

timestamp  method  id response
2009-01-10 getThud 16 "....."
2009-01-10 getFoo  12 "....."
2009-01-10 getBar  12 "....."
2009-01-11 getFoo  12 "....."
2009-01-11 getBar  16 "....."

想要的结果:

2009-01-10 getThud 16 "....."
2009-01-10 getBar 12 "....."
2009-01-11 getFoo 12 "....."
2009-01-11 getBar 16 "....."

(我不认为 this 是同一个问题 - 它不会给我最新的 response)

最佳答案

This solution was updated recently.
Comments below may be outdated

这个can查询可能执行得很好,因为没有连接。

SELECT * FROM (
    SELECT *,if(@last_method=method,0,1) as new_method_group,@last_method:=method 
    FROM rpc_responses 
    ORDER BY method,timestamp DESC
) as t1
WHERE new_method_group=1;

鉴于您希望每个 method 有一个结果行,这个解决方案应该可以工作,使用 mysql 变量来避免 JOIN。

仅供引用,PostgreSQL 有一种内置于语言中的方法:

SELECT DISTINCT ON (method) timestamp, method, id, response
FROM rpc_responses
WHERE 1 # some where clause here
ORDER BY method, timestamp DESC

关于mysql - 如何从 mysql 表中选择最新的日期记录集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/435703/

相关文章:

php - Top 5 排名问题

mysql - 为组选择 SUM() 的 Max()

mysql - 将姓氏与中缀拼接

SQL Convert(Date + Year(Date)) 在别人的代码中

python - 将字符串列表中的元素和下一个元素转换为 python 中的日期

javascript - 将 js knockout 到 mysql 数据库,使动态值不起作用

php - 单击按钮即可加载 +3 查询

php - 非常奇怪的mysql php blog 发生

mysql - 将包含特定日期的不常见值的表转换为包含一段时间内所有日期的表

MySQL:STR_TO_DATE 与 YYWW