商品表一个编号列,其他是商品基本信息列,
tb
ID,重量,重量1,金额,金额1。tb1
ID,字段名,修改时间,数值tb1里面字段名就是tb表中的“重量,重量1,金额,金额1”四列,只要修改tb中的这四列中其中一个就写一条到tb1中,如果4列都有修改,就写4条。现在要查询某个日期某个字段最新的数值select ID,,(select 数值from tb1 where ID=a.ID and 字段名='重量' and 修改时间=(select max(修改时间) from tb1 where ID=a.ID and col='重量'
修改时间<='2010-10-01'))
from tb a
现在数据量还不到1W,如果不要后面的子查询,1秒可以出来,这里有4列需要记录,加上4个子查询之后,要4-5秒,数据量还这么少,如果数据量大了,性能更差,大家帮忙看看有什么可以优化的没有。ID加了索引了。

解决方案 »

  1.   

    你换成join 或者exists试试,你的原始语句貌似筛选能力不强
      

  2.   


    没想到用join怎么做,因为join还得根据字段名过滤,而不仅仅是直接根据编号分组取最大。
      

  3.   

     with m
     as
     (
     select t.id,
            t.col,
            t.数值
     from tb t
     inner join
           (
     select  ID,
     COL,
     max(修改时间) as 修改时间
     from tb1
     where 修改时间<='2010-10-01'
       --and COL = '重量'
     group by id,
     col
           )tt
           on tt.id = t.id
              and tt.col = t.col  
              and tt.修改时间 = t.修改时间
     )   
           
     select a.*,
            m.数值
     from tb a
     left join m
            on a.id = m.id
               and a.字段名 = m.col  
      

  4.   


     with m
     as
     (
     select t.id,
            t.col,
            t.数值
     from tb t
     inner join
           (
     select  ID,
     COL,
     max(修改时间) as 修改时间
     from tb1
     where 修改时间<='2010-10-01'
       --and COL = '重量'
     group by id,
     col
           )tt
           on tt.id = t.id
              and tt.col = t.col  
              and tt.修改时间 = t.修改时间
     )   
           
     select a.*,
            m.数值
     from tb a
     left join m
            on a.id = m.id
               and a.字段名 = m.col  
      

  5.   

    你可以这样试试:select * from tb1 as a where not exists (select 1 from tb1 as b where a.[字段名]=b.[字段名] 
    and a.[修改时间]<b.[修改时间])
      

  6.   

    ;with cet as(select ID, 数值,ROW_NUMBER()over(PARTITION by ID order by 修改时间 desc) rn
     from tb1 where  字段名='重量' and 修改时间<='2010-10-01')
    select a.ID,b.数值
    from tb a ,CET b where a.ID = b.ID and b.rn = 1