qinxi
V2EX  ›  MySQL

mysql5.7 可以打破 索引 最左原则?

By qinxi at 2018 年 3 月 1 日 · 4324 次点击

根据 MYSQL 官网的文档 https://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html

查询条件要符合最左原则才能使用到索引

但是在实际测试(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, 则无法使用索引.

猜测是因为当字段都被索引时做出的优化?

4 条回复  •  2018-03-01 12:00:51 +08:00
doubleflower
   1
doubleflower  
   2018 年 3 月 1 日
这是用了索引取数据,没用上索引加速
qinxi
   2
qinxi  
OP
   2018 年 3 月 1 日
@doubleflower 我测试了一下 用索引加速查询的描述只有`Using index`?
richard1122
   3
richard1122  
   2018 年 3 月 1 日
possible_keys 是 null,没走你的那个索引。只是用了索引的数据。

如果你用 name 查会有 possible_keys 是你那个索引的。
qinxi
   4
qinxi  
OP
   2018 年 3 月 1 日
@richard1122 明白了
› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
© 2026 V2EX · 28ms · 3.9.8.5