查询条件要符合最左原则才能使用到索引
但是在实际测试(5.7.20 生效 5.6 不可重现)中 是可以打破最左原则的
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(25),
`sex` varchar(25) ,
`city` varchar(25) ,
PRIMARY KEY (`id`) USING BTREE,
INDEX `name`(`name`, `sex`, `city`) USING BTREE
)
mysql> EXPLAIN select * from `user` where sex='';
+----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+--------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+--------------------------+
| 1 | SIMPLE | user | NULL | index | NULL | name | 309 | NULL | 3 | 33.33 | Using where; Using index |
+----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+--------------------------+
1 row in set (0.02 sec)
这个是不是打破了最左原则??
测试中, 再新增一列 test. 再次执行以上 sql, 则无法使用索引.
猜测是因为当字段都被索引时做出的优化?