Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

最左原则,这种情况为什么会用到索引?

建表语句:

CREATE TABLE `user` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `name` char(10) NOT NULL,
  `nick_name` varchar(20) NOT NULL DEFAULT '' COMMENT '昵称',
  `job` varchar(20) NOT NULL DEFAULT '' COMMENT '职业',
  PRIMARY KEY (`id`),
  KEY `index_name` (`name`,`nick_name`,`job`)
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

插入的数据:
截屏2020-06-12 下午2.35.19.png

查询的语句:

explain select * from user where nick_name = 'ligoudan' and job = 'dog';

分析结果:

[
  {
    "id": 1,
    "select_type": "SIMPLE",
    "table": "user",
    "partitions": null,
    "type": "index",
    "possible_keys": "index_name",
    "key": "index_name",
    "key_len": "204",
    "ref": null,
    "rows": 3,
    "filtered": 33.33,
    "Extra": "Using where; Using index"
  }
]

查询的语句:

explain select * from user where job = 'ligoudan';

分析结果:

[
  {
    "id": 1,
    "select_type": "SIMPLE",
    "table": "user",
    "partitions": null,
    "type": "index",
    "possible_keys": "index_name",
    "key": "index_name",
    "key_len": "204",
    "ref": null,
    "rows": 3,
    "filtered": 33.33,
    "Extra": "Using where; Using index"
  }
]

我想不明白为什么会使用到索引,看了一些文章,最左原则,如果建了(a、b、c)的索引,说只有a 、ab 、abc会使用索引,可是我实际测试,b、c、bc这三种组合也使用到了索引,是我哪里理解不对么?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

自问自答,原因找到了,是因为覆盖索引的问题,虽然是select * ,但是所有的字段都是索引字段,所以走了覆盖索引逻辑,不再满足最左原则,参考文章:https://ostack.cn/a/11...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...