select count(*) from record where date > '19991201' and date '19991214'and amount > 2000 (25秒) select date,sum(amount) from record group by date (55秒) select count(*) from record where date > '19990901' and place in ('BJ','SH') (27秒)
select count(*) from record where date > '19991201' and date '19991214' and amount > 2000 (14秒) select date,sum(amount) from record group by date (28秒) select count(*) from record where date > '19990901' and place in ('BJ','SH')(14秒)
select count(*) from record where date > '19991201' and date '19991214' and amount > 2000 (26秒) select date,sum(amount) from record group by date (27秒) select count(*) from record where date > '19990901' and place in ('BJ, 'SH')( 1秒)
select count(*) from record where date > '19991201' and date '19991214' and amount > 2000( 1秒) select date,sum(amount) from record group by date (11秒) select count(*) from record where date > '19990901' and place in ('BJ','SH')( 1秒)
select * from record where substring(card_no,1,4)='5378'(13秒) select * from record where amount/30 1000(11秒) select * from record where convert(char(10),date,112)='19991201'(10秒)
select * from record where card_no like '5378%'( 1秒) select * from record where amount 1000*30( 1秒) select * from record where date= '1999/12/01' ( 1秒)
---- 你會發現SQL明顯快起來!
---- 2.例:表stuff有200000行,id_no上有非群集索引,請看下面這個SQL:
select count(*) from stuff where id_no in('0','1') (23秒)
---- 分析: ---- where條件中的'in'在邏輯上相當于'or',所以語法分析器會將in ('0','1')轉化為id_no ='0' or id_no='1'來執行。我們期望它會根據每個or子句分別查找,再將結果相加,這樣可以利用id_no上的索引;但實際上(根據showplan),它卻采用了"OR策略",即先取出滿足每個or子句的行,存入臨時數據庫的工作表中,再建立唯一索引以去掉重復行,最后從這個臨時表中計算結果。因此,實際過程沒有利用id_no上索引,并且完成時間還要受tempdb數據庫性能的影響。
select count(*) from stuff where id_no='0' select count(*) from stuff where id_no='1'
---- 得到兩個結果,再作一次加法合算。因為每句都使用了索引,執行時間只有3秒,在620000行下,時間也只有4秒。或者,用更好的方法,寫一個簡單的存儲過程: create proc count_stuff as declare @a int declare @b int declare @c int declare @d char(10) begin select @a=count(*) from stuff where id_no='0' select @b=count(*) from stuff where id_no='1' end select @c=@a+@b select @d=convert(char(10),@c) print @d