面試的時候總會問到索引的問題,而且一般會問到關於索引失效、哪種查詢會走索引,哪種方式不會這種問題。今天早上閑來無事對聯合索引進行了一些簡單的實驗,要測試的話肯定還有很多場景,在這里拋磚引玉。以后有機會再來完善此篇博客。
數據庫版本

建表語句
CREATE TABLE `union_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`a` varchar(8) COLLATE utf8_unicode_ci NOT NULL,
`b` varchar(8) COLLATE utf8_unicode_ci NOT NULL,
`c` varchar(8) COLLATE utf8_unicode_ci NOT NULL,
`createTime` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `union_index` (`a`,`b`,`c`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- records
INSERT INTO `union_test` VALUES ('1', 'a', 'b', 'c', '2017-08-16 10:41:48');
INSERT INTO `union_test` VALUES ('2', 'aa', 'bb', 'cc', '2017-08-16 10:41:56');
測試結果
EXPLAIN SELECT a,b,c FROM union_test WHERE a = "a" AND b = "b" AND c = "c" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE a = "a" AND b LIKE "b%" AND c LIKE "c%" -- 走索引,這里三個變量如果第一個是like就不走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE a = "a" AND c = "c" AND b = "b" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE b = "b" AND a = "a" AND c = "c" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE b = "b" AND c = "c" AND a = "a" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE c = "c" AND a = "a" AND b = "b" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE c = "c" AND b = "b" AND a = "a" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE a = "a" AND b = "b" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE b = "b" AND a = "a" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE a = "a" AND c = "c" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE c = "c" AND a = "a" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE b = "b" AND c = "c" -- 不走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE c = "c" AND b = "b" -- 不走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE a = "a" -- 走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE a LIKE "a%" -- 不走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE b = "b" -- 不走索引
EXPLAIN SELECT a,b,c FROM union_test WHERE c = "c" -- 不走索引
個人看法
這里可以看出如果是聯合索引的條件都存在的話,順序就不是問題了,似乎我之前理解的最左索引原則有錯誤,現在想想,如果條件里面含有聯合索引的第一個索引字段,那么不管where條件的順序和個數,則這次查詢都會走索引。上述如果使用了like,比如這樣SELECT a,b,c FROM union_test WHERE a LIKE "a%" AND b = "b%" AND c = "c%"會導致索引失效,單個索引的后半模糊不會導致索引失效,這里卻導致了索引失效,我沒想明白為什么,還是說如果是聯合索引,最左的索引字段就一定要是精確匹配呢?如果大神知道,還望告知,謝謝。
----后記
mysql中一般使用的都是B+樹來作為索引的數據存儲結構,所以一定要有一個索引的引導列,應該也就是B+樹的root節點,只有根節點存在才可以使用到聯合索引。
