V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
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
qinxi
V2EX  ›  MySQL

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

  •  
  •   qinxi · 2018-03-01 10:41:59 +08:00 · 3520 次点击
    这是一个创建于 2220 天前的主题,其中的信息可能已经有所发展或是发生改变。

    根据 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-03-01 10:59:05 +08:00
    这是用了索引取数据,没用上索引加速
    qinxi
        2
    qinxi  
    OP
       2018-03-01 11:31:07 +08:00
    @doubleflower 我测试了一下 用索引加速查询的描述只有`Using index`?
    richard1122
        3
    richard1122  
       2018-03-01 11:58:59 +08:00
    possible_keys 是 null,没走你的那个索引。只是用了索引的数据。

    如果你用 name 查会有 possible_keys 是你那个索引的。
    qinxi
        4
    qinxi  
    OP
       2018-03-01 12:00:51 +08:00
    @richard1122 明白了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5356 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 07:08 · PVG 15:08 · LAX 00:08 · JFK 03:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.