基于MYSQL的SQL語句優(yōu)化筆記

1.使用連接(JOIN)來代替子查詢(Sub-Queries)

2.應盡量避免在 where 子句中使用!=或<>操作符,否則將引擎放棄使用索引而進行全表掃描

3.應盡量避免在 where 子句中對字段進行 null 值判斷,否則將導致引擎放棄使用索引而進行全表掃描

如:select id from t where num is null

可以在num上設置默認值0,確保表中num列沒有null值,然后這樣查詢:

select id from t where num=0

4.應盡量避免在 where 子句中使用 or 來連接條件,否則將導致引擎放棄使用索引而進行全表掃描

如: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 也要慎用,否則會導致全表掃描,如:

select id from t where num in(1,2,3)

對于連續(xù)的數值,能用 between 就不要用 in 了:

select id from t where num between 1 and 3

7.應盡量避免在 where 子句中對字段進行表達式或函數操作,這將導致引擎放棄使用索引而進行全表掃描。如:

select id from t where num/2=100 應改為: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

應改為: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或者having,使用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)計行數

10.盡量少運算

11.盡量早過濾

12.能用inner join連接盡量使用inner join連接

13.使用JOIN時候,應該用小的結果驅動打的結果(left join 左邊表結果盡量小,如果有條件應該放到左邊先處理,right join同理反向),同事盡量把牽涉到多表聯合的查詢拆分多個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

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容