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

时间:2009-01-12 15:11:08

标签: 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)

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

7 个答案:

答案 0 :(得分: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

“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

答案 1 :(得分: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);

答案 2 :(得分: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!

答案 3 :(得分: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;

答案 4 :(得分:0)

我用过这个,为我工作

select max(timestamp),method,id from tables where 1 group by method,id order by timestamp desc 

答案 5 :(得分:-1)

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

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

SELECT timestamp,method,id,response 
FROM rpc_responses
HAVING max(timestamp) = timestamp 

答案 6 :(得分:-2)

...超过一年后,我可能会帮助别人 从最新的

开始选择所有查询
SELECT *
FROM rpc_responses
ORDER BY timestamp DESC
相关问题