1. 程式人生 > 其它 >MySQL索引失效實踐

MySQL索引失效實踐

匯入sql

CREATE TABLE `employees` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(24) NOT NULL DEFAULT '' COMMENT '姓名',
  `age` int(11) NOT NULL DEFAULT '0' COMMENT '年齡',
  `position` varchar(20) NOT NULL DEFAULT '' COMMENT '職位',
  `hire_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT
'入職時間', PRIMARY KEY (`id`), KEY `idx_name_age_position` (`name`,`age`,`position`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='員工記錄表'; INSERT INTO employees(name,age,position,hire_time) VALUES('LiLei',22,'manager',NOW()); INSERT INTO employees(name,age,position,hire_time)
VALUES('HanMeimei', 23,'dev',NOW()); INSERT INTO employees(name,age,position,hire_time) VALUES('Lucy',23,'dev',NOW());

最佳實踐

1. 全值匹配

EXPLAIN SELECT * FROM employees WHERE name= 'LiLei';
在這裡插入圖片描述
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22;
在這裡插入圖片描述
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22 AND position ='manager';


在這裡插入圖片描述

2.最佳左字首法則

如果索引了多列,要遵守最左字首法則。指的是查詢從索引的最左前列開始並且不跳過索引中的列。
EXPLAIN SELECT * FROM employees WHERE age = 22 AND position ='manager';
EXPLAIN SELECT * FROM employees WHERE position = 'manager';
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei';

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

EXPLAIN SELECT * FROM employees WHERE name = 'LiLei';
EXPLAIN SELECT * FROM employees WHERE left(name,3) = 'LiLei';
在這裡插入圖片描述

4.儲存引擎不能使用索引中範圍條件右邊的列

EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22 AND position ='manager';
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age > 22 AND position ='manager';
在這裡插入圖片描述

5.儘量使用覆蓋索引(只訪問索引的查詢(索引列包含查詢列)),減少select *語句

EXPLAIN SELECT NAME,age FROM employees WHERE NAME= 'LiLei' AND age = 23 AND POSITION ='manager';
在這裡插入圖片描述
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 23 AND position ='manager';
在這裡插入圖片描述

6.mysql在使用不等於(!=或者<>)的時候無法使用索引會導致全表掃描

EXPLAIN SELECT * FROM employees WHERE name != 'LiLei'
在這裡插入圖片描述

7.is null,is not null 也無法使用索引

EXPLAIN SELECT * FROM employees WHERE name is null
在這裡插入圖片描述

8.like以萬用字元開頭(’$abc…’)mysql索引失效會變成全表掃描操作

EXPLAIN SELECT * FROM employees WHERE name like '%Lei'
在這裡插入圖片描述
EXPLAIN SELECT * FROM employees WHERE NAME LIKE 'Lei%'
在這裡插入圖片描述

問題:解決like’%字串%'索引不被使用的方法?

a)使用覆蓋索引,查詢欄位必須是建立覆蓋索引欄位
EXPLAIN SELECT name,age,position FROM employees WHERE name like '%Lei%';
在這裡插入圖片描述
b)當覆蓋索引指向的欄位是varchar(380)及380以上的欄位時,覆蓋索引會失效!

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

EXPLAIN SELECT * FROM employees WHERE name = '1000';
在這裡插入圖片描述
EXPLAIN SELECT * FROM employees WHERE name = 1000;
在這裡插入圖片描述

10.少用or,用它連線時很多情況下索引會失效

EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' or name = 'HanMeimei';
在這裡插入圖片描述