mysql 單錶使用索引及常見的索引失效的情況總結

2021-10-19 20:23:16 字數 2841 閱讀 4479

目錄

單錶使用索引及常見的索引失效的情況

1. 全值匹配我最愛

1.1 有以下sql語句

1.2 建立索引

2. 最佳左字首法則

3. 不要在索引列上做任何操作

3.1 在查詢列上使用了函式

3.2 在查詢列上做了轉換

4. 索引列上有範圍查詢時,範圍條件右邊的列將失效

5. 使用不等於(!= 或者<>)的時候索引失效

6. is not null 不能使用索引,is null可以使用索引

7. like以萬用字元%或_開頭索引失效

8. 字串不加單引號索引失效

9. 減少使用or

10. 盡量使用覆蓋索引

結論:全職匹配我最愛指的是,查詢的字段按照順序在索引中都可以匹配到!

sql中查詢欄位的順序,跟使用索引中字段的順序,沒有關係。優化器會在不影響sql執行結果的前提下,給你自動地優化。

查詢欄位與索引字段順序的不同會導致,索引無法充分使用,甚至索引失效!

原因:使用復合索引,需要遵循最佳左字首法則,即如果索引了多列,要遵守最左字首法則。指的是查詢從索引的最左前列開始並且不跳過索引中的列。

結論:過濾條件要使用索引必須按照索引建立時的順序,依次滿足,一旦跳過某個字段,索引後面的字段都無法被使用。

不在索引列上做任何操作(計算、函式、(自動or手動)型別轉換),會導致索引失效而轉向全表掃瞄。

結論:等號左邊無計算!

create index idx_name on emp(name);

explain select sql_no_cache * from emp where name='30000';

explain select sql_no_cache * from emp where name=30000;

字串不加單引號,則會在name列上做一次轉換!

結論:等號右邊無轉換!

explain select sql_no_cache * from emp where emp.age=30 and deptid=5 and emp.name = 'abcd';

explain select sql_no_cache * from emp where emp.age=30 and deptid<5 and emp.name = 'abcd';

建議:將可能做範圍查詢的字段的索引順序放在最後

mysql 在使用不等於(!= 或者<>)時,有時會無法使用索引會導致全表掃瞄。

當欄位允許為null的條件下:

is not null用不到索引,is null可以用到索引。

字首不能出現模糊匹配!

使用union all或者union來替代:

即查詢列和索引列一致,不要寫select *!

explain  select sql_no_cache * from emp where emp.age=30  and deptid=4 and name='xamgxt';

explain  select sql_no_cache age,deptid,name  from emp where emp.age=30  and deptid=4 and name='xamgxt';

覆蓋索引是select的資料列只用從索引中就能夠取得,不必讀取資料行,換句話說查詢列要被所建的索引覆蓋

mysql 單 索引 mysql 單錶索引優化

建表語句 create table if not exists article id int 10 unsigned not null primary key auto increment,author id int 10 unsigned not null,category id int 10 u...

Mysql索引介紹及常見索引的區別

mysql索引概念 說說mysql索引,看到乙個很少比如 索引就好比一本書的目錄,它會讓你更快的找到內容,顯然目錄 索引 並不是越多越好,假如這本書1000頁,有500也是目錄,它當然效率低,目錄是要佔紙張的,而索引是要佔磁碟空間的。mysql索引主要有兩種結構 b tree索引和hash索引.ha...

mysql 索引 單錶優化

索引分析 type 為 all using filesort 自己進行了排序沒有用到索引 檢視 article 表有什麼索引 show index from article 只有乙個主鍵 建立索引 where 後面的字段需要建索引,但不一定必須建。嘗試著去建 alter table 表名 add i...