如何从mysql表中select最新的一组datelogging
我在下面的字段中存储了对mysql表中的各种rpc调用的响应:
Table: rpc_responses timestamp (date) method (varchar) id (varchar) response (mediumtext) PRIMARY KEY(timestamp,method,id)  selectmethod和id所有现有组合的最新答案的最佳方法是什么? 
- 
对于每个date,对于给定的方法/ ID只能有一个响应。 
- 
并非所有的通话组合都必须在给定的date。 
- 
有几十种方法,数以千计的ID和至less365个不同的date 
示例数据:
 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 ) 
谨慎使用此解决scheme:
它不能保证在未来版本的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 
自我回答,但我不确定这将是一个有效的解决scheme,随着表增长:
 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); 
尝试这个…
 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中使用!
我用这个,为我工作
 select max(timestamp),method,id from tables where 1 group by method,id order by timestamp desc 
当数据集变大时,子查询是非常重要的。
尝试这个:
 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; 
  “最近”的概念相当模糊。 如果你的意思是类似于最近的100行,那么你可以添加一个TOP(100)到你的SELECT子句。 
如果你的意思是“最近的”基于最近的date,那么你可以做
 SELECT timestamp,method,id,response FROM rpc_responses HAVING max(timestamp) = timestamp 
…超过一年后,但我可以帮助某人从最新开始select所有查询
 SELECT * FROM rpc_responses ORDER BY timestamp DESC