2010-09-20 62 views
2

只返回最新值我有一个表结构如下:从时间戳表

timestamp, tagid, value 

我想查询在那里我可以为标签ID的列表只接收最新的时间戳值。例如:

SELECT * FROM floatTable WHERE tagid IN(1,2,3,4,5,6) 

将返回整组值。我只想为每一个存储最新的值。

回答

3
select f.timestamp, f.tagid, f.value 
from floatTable f 
inner join (
    select tagid, max(timestamp) as timestampMax 
    from floatTable 
    where tagid in (1,2,3,4,5,6) 
    group by tagid 
) fm on f.tagid = fm.tagid and f.timestamp = fm.timestampMax 
+0

大根据需要它执行。但是,有没有办法加快速度?由于表格非常大,因此返回单个tagid值需要4-5秒。 – user438199 2010-09-20 16:33:34

0

如何:

select vt.tagid, maxdate, t.value 
from 
    ( 
    select tagid, max(timestamp) as maxdate 
    from floatTable 
    group by tagid 
) vt 
inner join floatTable t on t.tagid = vt.tagid 
where t.timestamp = vt.maxdate 
and t.tagid in (1,2,3,4,5,6)