1.使用連接(JOIN)來代替子查詢(Sub-Queries)
2.應(yīng)盡量避免在 where 子句中使用!=或<>操作符裹驰,否則將引擎放棄使用索引而進(jìn)行全表掃描
3.應(yīng)盡量避免在 where 子句中對字段進(jìn)行 null 值判斷删咱,否則將導(dǎo)致引擎放棄使用索引而進(jìn)行全表掃描
如:select id from t where num is null
可以在num上設(shè)置默認(rèn)值0,確保表中num列沒有null值肆汹,然后這樣查詢:
select id from t where num=0
4.應(yīng)盡量避免在 where 子句中使用 or 來連接條件,否則將導(dǎo)致引擎放棄使用索引而進(jìn)行全表掃描
如:select id from t where num=10 or num=20
可以這樣查詢:select id from t where num=10
????????????????????????????union all
????????????????????????????select id from t where num=20
5.盡量避免兩端模糊匹配like%***%
6.in 和 not in 也要慎用予权,否則會導(dǎo)致全表掃描昂勉,如:
select id from t where num in(1,2,3)
對于連續(xù)的數(shù)值,能用 between 就不要用 in 了:
select id from t where num between 1 and 3
7.應(yīng)盡量避免在 where 子句中對字段進(jìn)行表達(dá)式或函數(shù)操作扫腺,這將導(dǎo)致引擎放棄使用索引而進(jìn)行全表掃描岗照。如:
select id from t where num/2=100 應(yīng)改為:select id from t where num=100*2
如:select id from t where substring(name,1,3)='abc'--name以abc開頭的id
select id from t where datediff(day,createdate,'2005-11-30')=0--'2005-11-30'生成的id
應(yīng)改為:select id from t where name like 'abc%'
????????????select id from t where createdate>='2005-11-30' and createdate<'2005-12-1'
8.盡量避免在where子句中使用in,notin或者h(yuǎn)aving,使用exists,notexists代替:
select num from a where num in(select num from b)
替換:select num from a where exists(select 1 from b where num=a.num)
9.使用selectcount(*) 統(tǒng)計行數(shù)
10.盡量少運算
11.盡量早過濾
12.能用inner join連接盡量使用inner join連接
13.使用JOIN時候笆环,應(yīng)該用小的結(jié)果驅(qū)動打的結(jié)果(left join 左邊表結(jié)果盡量小攒至,如果有條件應(yīng)該放到左邊先處理,right join同理反向)躁劣,同事盡量把牽涉到多表聯(lián)合的查詢拆分多個query(多個表查詢效率低迫吐,容易鎖表和阻塞)。如:
Select * from A left join B ona.id=B.ref_id where B.ref_id>10;
可以優(yōu)化為:select * from (select * from A wehre id >10) T1 left join B onT1.id=B.ref_id;
14.盡量用union all 代替union