最近在做一个项目,需要频繁查询某张表monitor,表结构简单来说如下几个字段:
name type time resut
----------------------------------
name1 type1 time1 resut1
name2 type1 time1 resut2
name3 type2 time2 resut3
name4 type2 time2 resut4
name5 type3 time3 resut5
name6 type3 time3 resut6
name1 type1 time4 resut7
name2 type1 time4 resut8
. . . .
. . . .
. . . .
一个name属于某一类type,在某一time下有一个resut值;
在某一时刻by某一type来插入多条记录,即此时刻这类type下的所有name拥有共同的time,
一段时间后又插入这一type下的记录,如此继续下去。其它type同理。
现在要求页面输出的是最近time下的所有name的resut集合,
我用的最原始的实现方法:
select * from monitor where time=(select max(time) from monitor where type='type1') and type='type1'
union
select * from monitor where time=(select max(time) from monitor where type='type2') and type='type2'
union
select * from monitor where time=(select max(time) from monitor where type='type3') and type='type3'
union
......
union
......
结果上没有问题,但这样的查询速度似乎漫了点,特别是等到系统长期运行之后,当这张表的数据庞大之后,怕是要拖慢系统速度。想过用group功能,如下:
select * from monitor where time in(select max(time) from monitor group by type)
但查询结果不准,会有冗余数据,即某一type的最大max(time),恰好和另一type的历史time重合时,
会把另一type的历史数据也附带出来。还请高手赐教,谢谢!!!

解决方案 »

  1.   

    select a.*
    from monitor a,(select TYPE,MAX(time) time from monitor group by Type) b
    where a.type=b.type
    and a.time=b.time
      

  2.   


    select *
    from
    (
    select name,resut,
           row_number() over(partition by name,resut1 order by time desc) rn
    from tb1
    )
    where rn < 2
    不知道上面这个符合lz意思不   这个 最好贴出一些参考数据 然后贴出想得出的数据 不然意思不好理解