25

我将各种 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 "....."

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

4

7 回答 7

28

该解决方案最近已更新。
以下评论可能已过时

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

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
于 2012-09-27T16:11:23.303 回答
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);
于 2009-01-12T15:12:37.747 回答
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

...它甚至可以在 Access 中使用!

于 2010-07-06T11:05:27.743 回答
0

当数据集变大时,子查询非常费力。

试试这个:

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;
于 2011-07-26T16:40:01.663 回答
0

我用这个,为我工作

select max(timestamp),method,id from tables where 1 group by method,id order by timestamp desc 
于 2012-05-03T13:32:33.893 回答
-1

“最近”的概念相当模糊。如果您的意思是最近的 100 行,那么您可以在子句中添加TOP(100)一个SELECT

如果您的意思是基于最近日期的“最近”,那么您可以这样做

SELECT timestamp,method,id,response 
FROM rpc_responses
HAVING max(timestamp) = timestamp 
于 2009-01-12T15:22:37.180 回答
-4

...超过一年后,但我可能会帮助某人选择从最新开始的所有查询

SELECT *
FROM rpc_responses
ORDER BY timestamp DESC
于 2010-06-06T09:25:05.457 回答