共計(jì) 2524 個(gè)字符,預(yù)計(jì)需要花費(fèi) 7 分鐘才能閱讀完成。
本篇內(nèi)容介紹了“為什么 mysql 優(yōu)化器選擇了聚集索引”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓丸趣 TV 小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
通過(guò)這個(gè)以下這個(gè)案例,來(lái)說(shuō)明優(yōu)化器在選擇索引時(shí)候的取舍。
查看表結(jié)構(gòu):
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)
優(yōu)化器選擇 idx_id_orderseq,在意料之中,因?yàn)椴樵冏侄螢?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 |
+----+-------------+-------+------------+-------+--------------------------------+---------+---------+------+-------+----------+-------------+
優(yōu)化器選擇了 id 字段的聚集索引。因?yàn)槭?select *,所以優(yōu)化器沒(méi)有選擇索引 idx_id_orderseq(id,order_seq),id 字段的聚集索引(主鍵)和輔助索引 idx_id,優(yōu)化器是怎么選擇的呢?
如果選擇輔助索引 idx_id,查詢到具體 id 之后,還要回表查到整行的數(shù)據(jù)信息,雖然 id 字段是有序的,但是回表查詢的數(shù)據(jù)是無(wú)序的,因此變成了磁盤(pán)上的離散操作,離散讀取比順序讀取性能消耗高的多,所以會(huì)選擇聚集索引。
“為什么 mysql 優(yōu)化器選擇了聚集索引”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注丸趣 TV 網(wǎng)站,丸趣 TV 小編將為大家輸出更多高質(zhì)量的實(shí)用文章!