CREATE TABLE `user` (`id` int NOT NULL AUTO_INCREMENT,`age` int DEFAULT '0',`name` varchar(30) COLLATE utf8mb4_bin DEFAULT NULL,`info` varchar(20) COLLATE utf8mb4_bin DEFAULT NULL,PRIMARY KEY (`id`),KEY `idx_code_age_name` (`age`,`name`,`info`,),) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
# 增加联合索引,需要关注创建顺序ALTER TABLE table_name ADD INDEX idx_name (column1, column2);
只要最左边的 age 用到就可以启用索引
| sql | 是否使用到索引 | 解释 |
|---|---|---|
explain select * from user where age=21; |
用到了 | 第一个用了第一个age |
explain select * from user where age=21 and name='小明' |
用到了 | 第一个用了第一个age |
explain select * from user where age=21 and name='小明' and info='101'; |
用到了 | 第一个用了第一个age |
explain select * from user where age=21 and info='101'; |
用到了 | 第一个用了第一个age |
explain select * from user where name='小明'; |
失效了 | 第一个没用了第一个age |
explain select * from user where info='101'; |
失效了 | 第一个没用了第一个age |
explain select * from user where name='小明' and info='101'; |
失效了 | 第一个没用了第一个age |