在查詢時,MySQL有機會將利用不同索引查詢得到的結果進行合併彙總得到最後結果。
舉例:SELECT * FROM table_1 WHERE column_1 = value_1 AND column_2 = value_2;
假設table_1上存在索引idx_column1和idx_column2,原本相對合適的索引應該是idx_best = (column_1, column_2)的聯合索引,但是現在只有兩列單獨的索引,因此MySQL可能將原查詢拆分成:
SELECT * FROM table_1 WHERE column_1 = value_1;
SELECT * FROM table_1 WHERE column_2 = value_2;
得到兩份結果並且取交集(Intersection),特徵爲Explain查詢中Extra欄顯示:
Using intersect(idx_column1, idx_column2)
同樣:SELECT * FROM table_1 WHERE column_1 = value_1 OR column_2 = value_2;
此時可能會拆分取並集,Extra顯示:
Using union(idx_column1, idx_column2)
Explain結果示例:
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | table1 | index_merge | idx_colulmn1,idx_column2 | column1,idx_column2 | 5,5 | NULL | 8642 | Using union(idx_column1,idx_column2);Using where |
- 錯誤、低效的索引將會極大降低查詢的性能,因爲低效的索引拆分查詢的結果可能相當大,導致取交集的運算非常緩慢