標籤:
MySQL5.0之前,一條語句中一個表只能使用一個索引,無法同時使用多個索引。但是從5.1開始,引入了 index merge 最佳化技術,對同一個表可以使用多個索引。理解了 index merge 技術,我們才知道應該如何在表上建立索引。
相關文檔:http://dev.mysql.com/doc/refman/5.6/en/index-merge-optimization.html (注意該文檔中說的有幾處錯誤)
The Index Merge method is used to retrieve rows with several range scans and to merge their results into one. The merge can produce unions, intersections, or unions-of-intersections of its underlying scans. This access method merges index scans from a single table; it does not merge scans across multiple tables.
In EXPLAIN output, the Index Merge method appears as index_merge in the type column. In this case, the key column contains a list of indexes used, and key_len contains a list of the longest key parts for those indexes.
index merge: 同一個表的多個索引的範圍掃描可以對結果進行合并,合并方式分為三種:union, intersection, 以及它們的各種組合。
Examples:
SELECT * FROM tbl_name WHERE key1 = 10 OR key2 = 20;SELECT * FROM tbl_name WHERE (key1 = 10 OR key2 = 20) AND non_key=30;SELECT * FROM t1, t2 WHERE (t1.key1 IN (1,2) OR t1.key2 LIKE ‘value%‘) AND t2.key1=t1.some_col;SELECT * FROM t1, t2 WHERE t1.key1=1 AND (t2.key1=t1.some_col OR t2.key2=t1.some_col2);
文檔這裡是有錯誤的:最後一個select語句, t2.key1=t1.some_col OR t2.key2=t1.some_col2,因為這裡使用的是 OR,所以這裡是無法使用複合式索引的。
The Index Merge method has several access algorithms (seen in the Extra field of EXPLAIN output):
Using intersect(...)
Using union(...)
Using sort_union(...)
根據索引合并的方式不同,會在explain結果中顯示使用了那種合并方法。
一般而且出現了 Index merge 並不一定是什麼好事。比如一般出現了 Using intersect 的執行計畫,預示著我們索引的建立不是最佳的,一般可以通過建立符合索引來進一步進行最佳化,可以參考文章:https://www.percona.com/blog/2009/09/19/multi-column-indexes-vs-index-merge/
MySQL 最佳化之 index merge(索引合并)