|
让SQL运行得更快 /******组合索引,前导列 .在place,date,amount上的组合索引
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秒)
---- 分析: ---- 这是一个不很合理的组合索引,因为它的前导列是place,第一和第二条SQL没有引用place,因此也没有利用上索引;第三个SQL使用了place,且引用的所有列都包含在组合索引中,形成了索引覆盖,所以它的速度是非常快的。
/******最佳查询方案是将card作外层表,account作内层表,利用account上的索引, 例:表card有7896行,在card_no上有一个非聚集索引,表account有191122行,在 account_no上有一个非聚集索引,试看在不同的表连接条件下,两个SQL的执行情况:
select sum(a.amount) from account a, card b where a.card_no = b.card_no(20秒)
---- 将SQL改为: select sum(a.amount) from account a, card b where a.card_no = b.card_no and a. Account_no=b.account_no(< 1秒)
----
/******任何对列的操作都将导致表扫描,它包括数据库函数、计算表达式等等,查询时要尽可能将操作移至等号右边。 1.例:下列SQL条件语句中的列都建有恰当的索引,但执行速度却非常慢:
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秒)
---- 分析: ---- where子句中对列的任何操作结果都是在SQL运行时逐列计算得到的,因此它不得不进行表搜索,而没有使用该列上面的索引;如果这些结果在查询编译时就能得到,那么就可以被SQL优化器优化,使用索引,避免表搜索,因此将SQL重写成下面这样:
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秒)"
|