专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > SQL

查询表中相同字段按时间排序(时间最大)的记录,该如何处理

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
查询表中相同字段按时间排序(时间最大)的记录
表 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复合索引试试
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: