查询表中相同字段按时间排序(时间最大)的记录
表 executions
id build_id tester_id execution_ts status testplan_id tcversion_id
653 114 1 2011-05-29 19:36:42 p 3609 8469
654 114 1 2011-05-29 19:39:15 f 3609 8469
如果要查询出tcversion_id相同记录中 execution_ts 时间最大的那条记录,请问sql如何写?
以下sql语句查询出来的结果不正确
SELECT id,tcversion_id ,MAX(execution_ts) ,status FROM executions GROUP BY tcversion_id
该方法可以查询出,但速度特别慢,executions有10万条数据,查询时间至少半个小时了,不可行,请高手赐教!
select * from executions t
where not exists (select 1 from executions where tcversion_id=t.tcversion_id and execution_ts>t.execution_ts)
[解决办法]
select * from executions t
where not exists (select 1 from executions where tcversion_id=t.tcversion_id and execution_ts>t.execution_ts)
应该可以 ,在tcversion_id上建立索引试试
也可以
select t.* from executions t inner join
(select tcversion_id,max(execution_ts) as ma from executions group by tcversion_id) b
on t.tcversion_id=b.tcversion_id and t.execution_ts=b.ma
[解决办法]
参考下贴中的多种方法
http://topic.csdn.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
[征集]分组取最大N条记录方法征集,及散分....
[解决办法]
建议你在 executions 表上创建 (tcversion_id,execution_ts)的联合索引。
[解决办法]
select t.* from executions t inner join
(select tcversion_id,max(execution_ts) as ma from executions group by tcversion_id) b
on t.tcversion_id=b.tcversion_id and t.execution_ts=b.ma
这个是可以的
10W条数据要半小时 太慢了吧。。。
[解决办法]
什么数据库?
如果 在tcversion_id上建立索引速度不明显,建立
tcversion_id、execution_ts复合索引试试