› 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 · Mar 1, 2018 · 4327 views
    This topic created in 3133 days ago, the information mentioned may be changed or developed.

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

    如果你用 name 查会有 possible_keys 是你那个索引的。
    qinxi
        4
    qinxi  
    OP
       Mar 1, 2018
    @richard1122 明白了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1122 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 17:29 · PVG 01:29 · LAX 10:29 · JFK 13:29
    ♥ Do have faith in what you're doing.