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

47次阅读
没有评论

共计 2524 个字符,预计需要花费 7 分钟才能阅读完成。

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

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

查看表结构:

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 优化器选择了聚集索引”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注丸趣 TV 网站,丸趣 TV 小编将为大家输出更多高质量的实用文章!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-07-27发表,共计2524字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)