数据表这样的几个列 基本数据如下:
   Id             发布时间        有效期(天)    列A    列B   列C   列D
   1                2012-2-4         30          a1      b1     c1    d1
   2                2012-2-4          0           a2      b2     c1    d2
   3                2012-2-3          1           a1      b1     c1    d1
   4                2012-2-5          0           a2      b2     c1    d2
 …………………………………………………………………………………………………………
其中 有效期中的0表示永不失效
现在需要显示的数据是 不过期 的数据,以查询日期为准。,请问这样的查询如何写才能优化。谢谢(Sql2005)

解决方案 »

  1.   


    declare @T table 
    (
    Id int,发布时间 datetime,有效期 int,
    列A varchar(2),列B varchar(2),列C varchar(2),列D varchar(2)
    )
    insert into @T
    select 1,'2012-2-4',30,'a1','b1','c1','d1' union all
    select 2,'2012-2-4',0,'a2','b2','c1','d2' union all
    select 3,'2012-4-3',15,'a1','b1','c1','d1' union all
    select 4,'2012-2-5',0,'a2','b2','c1','d2'select * from @T 
    where 有效期=0 or dateadd(d,有效期,发布时间)>=getdate()
    /*
    Id          发布时间                    有效期         列A   列B   列C   列D
    ----------- ----------------------- ----------- ---- ---- ---- ----
    2           2012-02-04 00:00:00.000 0           a2   b2   c1   d2
    3           2012-04-03 00:00:00.000 15          a1   b1   c1   d1
    4           2012-02-05 00:00:00.000 0           a2   b2   c1   d2
    */
      

  2.   

    3楼的where条件语句也可以直接这样写,这样如果数据多,看能都利用上索引。
    select * from @T 
    where 有效期=0
      or 发布时间 > getdate() - [有效期]
      

  3.   

    我写的是 select * from @T 
    where 有效期=0
      or ((发布时间 > getdate() - [有效期])and 有效期 !=0)
    查询是查出来了,但是很慢,有没有更好的办法
      

  4.   

    首先你前面的改的那个where条件里面后面的 有效期 !=0 是多余的,没有必要。
    or ((发布时间 > getdate() - [有效期])and 有效期 !=0)
    其次,30万的数据量算小的了,不大,但是按照目前的 where 条件语句,估计对于 [有效期] 字段需要全表扫描了,具体你可以看看执行计划。
    另外想问你的执行时间是多少?目标时间是多少?另外能否新加一个字段,字段取值为:  发布时间 + (case 有效期 when 0 then 100000000 else 有效期 end),在这个字段建索引,扫描速度肯定快了。
      

  5.   

    实现代码没什么问题,3楼叶子的就OK。
    至于效率,建议楼主如果ID字段是唯一值,不为空,可以在ID字段建立聚集索引,这样查询的时候会走聚集索引扫描。
    光在“发布时间”上建立索引是没用的,查询的时候走的是全表扫描。
      

  6.   

    试试下面这个语句,最好建议楼主,分析一下是什么地方慢或者提供多点信息,不然很难帮上你。select * from tabname
    where 有效期=0 
    union all
    select * from tabname
    where 发布时间 > getdate() - [有效期]