查询表中相同字段按时间排序(时间最大)的记录

yangdaliang 2011-05-30 11:31:20
表 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)
...全文
171 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ACMAIN_CHM 2011-05-30
  • 打赏
  • 举报
回复
建议你在 executions 表上创建 (tcversion_id,execution_ts)的联合索引。
ACMAIN_CHM 2011-05-30
  • 打赏
  • 举报
回复
参考下贴中的多种方法

http://topic.csdn.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
[征集]分组取最大N条记录方法征集,及散分....
WWWWA 2011-05-30
  • 打赏
  • 举报
回复
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
wwwwb 2011-05-30
  • 打赏
  • 举报
回复
什么数据库?
如果 在tcversion_id上建立索引速度不明显,建立
tcversion_id、execution_ts复合索引试试
加油馒头 2011-05-30
  • 打赏
  • 举报
回复
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条数据要半小时 太慢了吧。。。

2,596

社区成员

发帖
与我相关
我的任务
社区描述
Sybase相关技术讨论区
社区管理员
  • Sybase社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧