我将各种 rpc 调用的响应存储在一个 mysql 表中,其中包含以下字段:
Table: rpc_responses
timestamp (date)
method (varchar)
id (varchar)
response (mediumtext)
PRIMARY KEY(timestamp,method,id)
为 method
和 id
的所有现有组合选择最新响应的最佳方法是什么?
对于给定的方法/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/