一、常見例子
mysql索引最左匹配原則主要是針對複合索引(聯合索引)來說的,比如你在字段 a,b,c 建立了一個聯合索引 index_abc
ALTER TABLE `test`
ADD INDEX `index_abc`(`a`,`b`, `c`) USING BTREE;
-
explain select * from test where a<10 ; # 用索引
-
explain select * from test where a<10 and b <10; # 用索引
-
explain select * from test where a<10 and b <10 and c<10; # 用索引
能不能將 a,b出現順序換一下,a,b,c出現順序換一下
- explain select * from test where b<10 and a <10; # 用索引
5. explain select * from test where b<10 and a <10 and c<10; # 用索引
- explain select * from test where b<10 and c <10;# 用不到索引
-
explain select * from test where a<10 and c <10; # a 能用到索引, c用不到
-
explain select * from test where a=1001 #用到索引
-
explain select * from test where a=1001 and b=1002 #用到索引
-
explain select * from test where b=1002 and a=1001 # 用到索引,mysql 優化器會將 sql優化成:explain select * from test where a=1001 and b=1002
- explain select * from test where a=1001 and c=1003 # a 能用到索引,c用不到
- explain select * from test where c=1003 # 用不到索引
- explain select * from test where b=1002 # 用不到索引
二、總結
如果有複合索引 index_abc(a,b,c),且是select * 則
- 只要保證 a 字段能夠出現在where條件後,不論 a 出現的先後順序,就一定能用索引 (適用於查詢條件是 “=” )
- a 是查詢條件的第一個條件則一定能用索引(適用於查詢條件是 “=”,"<" , “>”)
- 查詢條件只有 b 或 c 或 b c 則不能使用索引
一般在面試的時候查詢條件是“=” 且前邊都是select * 如果不是這樣則上邊的結論不成立