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

2018-03-01 10:41:59 +08:00
 qinxi

根据 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, 则无法使用索引.

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

3537 次点击
所在节点    MySQL
4 条回复
doubleflower
2018-03-01 10:59:05 +08:00
这是用了索引取数据,没用上索引加速
qinxi
2018-03-01 11:31:07 +08:00
@doubleflower 我测试了一下 用索引加速查询的描述只有`Using index`?
richard1122
2018-03-01 11:58:59 +08:00
possible_keys 是 null,没走你的那个索引。只是用了索引的数据。

如果你用 name 查会有 possible_keys 是你那个索引的。
qinxi
2018-03-01 12:00:51 +08:00
@richard1122 明白了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/433796

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX