您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“為什么mysql優(yōu)化器選擇了聚集索引”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
通過這個以下這個案例,來說明優(yōu)化器在選擇索引時候的取舍。
查看表結(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,在意料之中,因為查詢字段為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字段的聚集索引。因為是select *,所以優(yōu)化器沒有選擇索引idx_id_orderseq(id,order_seq),id字段的聚集索引(主鍵)和輔助索引idx_id,優(yōu)化器是怎么選擇的呢?
如果選擇輔助索引idx_id,查詢到具體id之后,還要回表查到整行的數(shù)據(jù)信息,雖然id字段是有序的,但是回表查詢的數(shù)據(jù)是無序的,因此變成了磁盤上的離散操作,離散讀取比順序讀取性能消耗高的多,所以會選擇聚集索引。
“為什么mysql優(yōu)化器選擇了聚集索引”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。