为什么优化器选择了聚集索引?

通过这个以下这个案例,来说明优化器在选择索引时候的取舍。

查看表结构:

MySQL > show create table test2 \G
*************************** 1. row ***************************
       Table: test2
Create Table: CREATE TABLE `test2` (
  `id` bigint(16) NOT NULL AUTO_INCREMENT,
  `order_seq` bigint(16) NOT NULL,
  `order_type` int(11) DEFAULT NULL,
  `order_flag` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_id` (`id`),
  KEY `idx_id_orderseq` (`id`,`order_seq`)
) ENGINE=InnoDB AUTO_INCREMENT=15002212 DEFAULT CHARSET=utf8mb4
1 row in set (0.00 sec)

查询一:

MySQL > explain select id,order_seq from test2 where id>10000 and id<20000;
+----+-------------+-------+------------+-------+--------------------------------+-----------------+---------+------+-------+----------+--------------------------+
| id | select_type | table | partitions | type  | possible_keys                  | key             | key_len | ref  | rows  | filtered | Extra                    |
+----+-------------+-------+------------+-------+--------------------------------+-----------------+---------+------+-------+----------+--------------------------+
|  1 | SIMPLE      | test2 | NULL       | range | PRIMARY,idx_id,idx_id_orderseq | idx_id_orderseq | 8       | NULL | 18484 |   100.00 | Using where; Using index |
+----+-------------+-------+------------+-------+--------------------------------+-----------------+---------+------+-------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)

优化器选择idx_id_orderseq,在意料之中,因为查询字段为id,order_seq,可以利用覆盖索引。

查询二:

MySQL > explain select * from test2 where id>10000 and id<20000;
+----+-------------+-------+------------+-------+--------------------------------+---------+---------+------+-------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys                  | key     | key_len | ref  | rows  | filtered | Extra       |
+----+-------------+-------+------------+-------+--------------------------------+---------+---------+------+-------+----------+-------------+
|  1 | SIMPLE      | test2 | NULL       | range | PRIMARY,idx_id,idx_id_orderseq | PRIMARY | 8       | NULL | 19122 |   100.00 | Using where |
+----+-------------+-------+------------+-------+--------------------------------+---------+---------+------+-------+----------+-------------+

优化器选择了id字段的聚集索引。因为是select *,所以优化器没有选择索引idx_id_orderseq(id,order_seq),id字段的聚集索引(主键)和辅助索引idx_id,优化器是怎么选择的呢?

如果选择辅助索引idx_id,查询到具体id之后,还要回表查到整行的数据信息,虽然id字段是有序的,但是回表查询的数据是无序的,因此变成了磁盘上的离散操作,离散读取比顺序读取性能消耗高的多,所以会选择聚集索引。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值