MySQL 最佳化之 index merge(索引合并)

來源:互聯網
上載者:User

標籤:

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(索引合并)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.