Ken*_*Ken 25 mysql sql date greatest-n-per-group
我将响应存储在mysql表中的各种rpc调用中,其中包含以下字段:
Table: rpc_responses
timestamp (date)
method (varchar)
id (varchar)
response (mediumtext)
PRIMARY KEY(timestamp,method,id)
Run Code Online (Sandbox Code Playgroud)
什么是选择最近期的所有现有组合响应的最佳方法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 "....."
Run Code Online (Sandbox Code Playgroud)
期望的结果:
2009-01-10 getThud 16 "....."
2009-01-10 getBar 12 "....."
2009-01-11 getFoo 12 "....."
2009-01-11 getBar 16 "....."
Run Code Online (Sandbox Code Playgroud)
(我不认为这是同一个问题 - 它不会给我最新的response
)
vel*_*row 28
谨慎使用此解决方案:
不保证在未来的mysql版本中
可以使用它不知道在mariadb 5.5中工作
这可以查询可能表现良好,因为没有连接.
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
Run Code Online (Sandbox Code Playgroud)
"group by"会折叠方法上的结果集,并且每个方法只返回1行,最新的一行,因为内部查询中的ORDER BY时间戳DESC.
仅供参考,PostgreSQL有一种方法可以在语言中构建:
SELECT DISTINCT ON (method) timestamp, method, id, response
FROM rpc_responses
WHERE 1 # some where clause here
ORDER BY method, timestamp DESC
Run Code Online (Sandbox Code Playgroud)
Ken*_*Ken 14
自我回答,但我不确定随着表格的增长,它将是一个足够有效的解决方案:
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);
Run Code Online (Sandbox Code Playgroud)
小智 6
试试这个...
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
Run Code Online (Sandbox Code Playgroud)
......它甚至适用于Access!
归档时间: |
|
查看次数: |
98196 次 |
最近记录: |