一 介紹 MySQL 5.6版本提供了很多性能優化的特性,其中之一就是 Multi-Range Read 多范圍讀(MRR) , 它的作用針對基于輔助/第二索引的查詢,減少隨機IO,并且將隨機IO轉化為順序IO,提高查詢效率。 二 原理 在沒有MRR之前,或者沒有開啟MRR特性時,MySQL 針對基于輔助索引的查詢策略是這樣的: select non_key_column from tb wherekey_column=x; MySQL 執行查詢的偽代碼 第一步 先根據where條件中的輔助索引獲取輔助索引與主鍵的集合,結果集為rest。 select key_column, pk_column from tb where key_column=x order by key_column 第二步 通過第一步獲取的主鍵來獲取對應的值。 for each pk_column value in rest do: select non_key_column from tb where pk_column=val
在使用MRR優化特性的情況下,MySQL 針對基于輔助索引的查詢策略是這樣的: 第一步 先根據where條件中的輔助索引獲取輔助索引與主鍵的集合,結果集為rest select key_column, pk_column from tb where key_column = x order by key_column 第二步 將結果集rest放在buffer里面(read_rnd_buffer_size 大小直到buffer滿了),然后對結果集rest按照pk_column排序,得到結果集是rest_sort 第三步 利用已經排序過的結果集,訪問表中的數據,此時是順序IO. select non_key_column fromtb where pk_column in ( rest_sort )
MySQL > explain select * from tbl where tbl.key1 between 1000 and 2000; +----+-------------+-------+-------+---------------+------+---------+------+------+-------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+------+---------+------+------+-------------------------------------------+ | 1 | SIMPLE | tbl | range | key1 | key1 | 5 | NULL | 960 | Using index condition; Using MRR | +----+-------------+-------+-------+---------------+------+---------+------+------+-------------------------------------------+ 1 row in set (0.03 sec) 五 MRR的使用限 MRR 適用于以下兩種情況。 1 range access 2 ref and eq_ref access, when they are using Batched Key Access.