1. 程式人生 > 其它 >MySQL 面試題: 索引什麼時候會失效

MySQL 面試題: 索引什麼時候會失效

表情況

 

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
  `age` int DEFAULT '0',
  `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
  `height` int DEFAULT '0',
  `address` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
   PRIMARY KEY (`id`),
   KEY `idx_code_age_name` (`code`,`age`,`name`),
   KEY `idx_height` (`height`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

INSERT INTO user (id, code, age, name, height) VALUES (1, '101', 21, '周星馳', 175,'香港');
INSERT INTO user (id, code, age, name, height) VALUES (2, '102', 18, '周杰倫', 173,'臺灣');
INSERT INTO user (id, code, age, name, height) VALUES (3, '103', 23, '蘇三', 174,'成都');

 

索引可能失效的情況

 

下面的法則不要死記,本質是系統通過計算查詢資料開銷的結果,那種方式快使用那種。

 

  1. 使用聯合索引時不滿足最左匹配原則。
  # 聯合索引 code,age,name

  # 使用索引的情況,索引先排第一列的序再排第二列的序,以此類推
  explain select * from user where code='101';
  explain select * from user where code='101' and age=21
  explain select * from user where code='101' and age=21 and name='周星馳';

  # 索引失效的情況
  explain select * from user where age=21;
  explain select * from user where name='周星馳';
  explain select * from user where age=21 and name='周星馳';

 

  1. 使用了 select *
  # 全表掃描
  explain  select * from user where name='蘇三';
  
  # 索引掃描
  explain  select code,name from user  where name='蘇三';

 

  1. 索引上有計算或函式( 可能)
  # 全表掃描 ALL
  explain  select * from user where id+ 1=2;

  # 索引掃描 idx_code_age_name
  explain  select name from user where id + 1=2;

 

  1. like 左邊包含%
  # 全表掃描 ALL
  explain select * from user where name like '李%';

  # 索引掃描 idx_code_age_name
  explain  select name from user where id + 1=2;