数据表这样的几个列 基本数据如下:
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)
------解决方案--------------------
- SQL code
declare @T table ( Id int,发布时间 datetime,有效期 int, 列A varchar(2),列B varchar(2),列C varchar(2),列D varchar(2))insert into @Tselect 1,'2012-2-4',30,'a1','b1','c1','d1' union allselect 2,'2012-2-4',0,'a2','b2','c1','d2' union allselect 3,'2012-4-3',15,'a1','b1','c1','d1' union allselect 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 d23 2012-04-03 00:00:00.000 15 a1 b1 c1 d14 2012-02-05 00:00:00.000 0 a2 b2 c1 d2*/
------解决方案--------------------
首先你前面的改的那个where条件里面后面的 有效期 !=0 是多余的,没有必要。
- SQL code
or ((发布时间 > getdate() - [有效期])and 有效期 !=0)
------解决方案--------------------
试试下面这个语句,最好建议楼主,分析一下是什么地方慢或者提供多点信息,不然很难帮上你。
- SQL code
select * from tabnamewhere 有效期=0 union allselect * from tabnamewhere 发布时间 > getdate() - [有效期]