天天看點

MYSQL索引優化法則

目錄

一首詩送給各位:

全值比對我最愛,最左字首要遵守;

帶頭大哥不能死,中間兄弟不能斷;

索引列上少計算,範圍之後全失效;

Like百分寫最右,覆寫索引不寫星;

不等空值還有or,索引失效要少用;

VAR引号不可丢,SQL進階也不難!

舉個栗子:

假設index(a,b,c)

where語句 索引是否被用到 原因
where a=3 使用到a 全值比對
where a=3 and b=5 使用到a,b 全值比對
where a=3 and b=5 and c=4 使用到a,b,c 全值比對
where b=3 or where b=3 and c=4 or where c=4 NULL 因為按照建立索引的順序第一個索引列a沒有被用到,導緻後面的索引失效。
where a=3 and c=5 使用到a b沒有被用到,導緻c失效
where a=3 and b>4 and c=5 使用到a b為範圍查詢索引失效導緻C也失效
where a=3 and b like 'kk%' and c =4 使用到a,b,c 這裡的b是可以用到的因為百分号在最右結合最左字首原則,雖然%相當于範圍查詢但是在最右,最左邊是定值。
where a=3 and b like '%kk' and c=4 使用到a b中間斷開失效導緻c也失效
where a=3 and b like '%kk%' and c=4 使用到a b斷開
where a=3 and b like 'k%kk%' and c=4 使用到a,b,c 同上上上

繼續閱讀