温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-11-01 09:27:09 来源:亿速云 阅读:108 作者:iii 栏目:MySQL数据库

本篇内容介绍了“为什么mysql优化器选择了聚集索引”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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

查看表结构:

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字段是有序的,但是回表查询的数据是无序的,因此变成了磁盘上的离散操作,离散读取比顺序读取性能消耗高的多,所以会选择聚集索引。

“为什么mysql优化器选择了聚集索引”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI