1.准备表sales
CREATE TABLE `sales` (
`id` int NOT NULL,
`year` int DEFAULT NULL,
`country` varchar(20) DEFAULT NULL,
`product` varchar(20) DEFAULT NULL,
`profit` int DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_name` (`profit`),
KEY `idx_name2` (`product`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
2.左模糊匹配可以看到走的是全表ALL
SELECT * from sales where product like '%f%';
如果开头不是%开头的就会走索引比如SELECT * from sales where product like 'f%';可以看到他就会走索引
2.隐式的类型转换
product是varchar类型查询的时候给int类型这个时候就不会走索引了
给条件是varchar就会走索引
3.使用联合索引时,列的顺序错误
使用联合索引需要满足最左匹配原则,即最左优先。如果你建立一个(country, product, profit)的联合索引,相当于建立了 (country)、(product,product)、(country,product,profit) 三个索引。如下例子country没有在查询条件内,所以不会走索引
county在查询条件内,可以看到就走了索引,当建立了联合索引的时候查询的时候一定要带上最左边的字段索引才会走索引。