日期:2014-05-18  浏览次数:20595 次

这条语句还能优化吗
SQL code

--这条语句还能优化吗 大概100W的数据量

select id,account,email,mobile from users where (datediff(yyyy,birthday,getdate())>=20) and ((CreditCoin>1999 and CreditCoin<=3999) or (CreditCoin>999 and CreditCoin<=1999) or (CreditCoin>399 and CreditCoin<=999) or (CreditCoin>99 and CreditCoin<=399) or (CreditCoin>29 and CreditCoin<=99) or isnull(CreditCoin,0) <= 29 or (CreditCoin>=4000))



------解决方案--------------------
单从语句看,基本无法优化,还得看索引和数据分布的情况..

问题是,如何处理这100W数据?真有必要一次取出这么多?
------解决方案--------------------
select id,account,email,mobile from users 
where (datediff(yyyy,birthday,getdate())>=20)
就好,你的那个CreditCoin条件没有用
------解决方案--------------------
SQL code
select id,account,email,mobile 
from users 
where birthday <= dateADD(yyyy,-20,getdate())

------解决方案--------------------
把 OR 用 union all 替换,虽然语句长点,但是效率会提高,尤其是百万级以上数据。 OR 要全表扫描。
------解决方案--------------------
birthday 建立索引
------解决方案--------------------
探讨

birthday 建立索引

------解决方案--------------------
探讨
后面那一长串OR是会员的信誉等级,等级在某个区间,如下:

C# code


case "F": values += " or isnull(CreditCoin,0) <= 29"; break;
case "E": values += " or (CreditCoin>29 and CreditCoin<=99)"; break;
……

------解决方案--------------------
SQL code

(datediff(yyyy,birthday,getdate())>=20)--这种不使用索引
birthday<=dateadd(yy,-20,getdate())--这种使用索引