今天在处理数据时用到了mysql的联合索引,就是否使用到索引,总结备案下(欢迎指正,至于使用到的索引效率没测试)。
环境:mysql5.6
数据表:
CREATE TABLE `test` (
`f1` int(11) NOT NULL,
`f2` int(11) NOT NULL,
`f3` int(11) NOT NULL,
`f4` int(11) NOT NULL,
`f5` int(11) NOT NULL,
UNIQUE KEY `f123` (`f1`,`f2`,`f3`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='测试表';
测试语句:
#使用联合索引所有字段后,测试顺序是否影响,结果是没影响的
EXPLAIN select * from test where f1=1 and f2=1 and f3=1;
EXPLAIN select * from test where f1=1 and f3=1 and f2=1;
EXPLAIN select * from test where f2=1 and f1=1 and f3=1;
EXPLAIN select * from test where f2=1 and f3=1 and f1=1;
EXPLAIN select * from test where f3=1 and f1=1 and f2=1;
EXPLAIN select * from test where f3=1 and f2=1 and f1=1;
#使用联合索引任意两个字段后,测试顺序是否影响,结果是没影响的
EXPLAIN select * from test where f1=1 and f2=1;
EXPLAIN select * from test where f2=1 and f1=1;
EXPLAIN select * from test where f1=1 and f3=1;
EXPLAIN select * from test where f3=1 and f1=1;
EXPLAIN select * from test where f2=1 and f3=1;
EXPLAIN select * from test where f3=1 and f2=1;
#使用联合索引一个字段查询后,测试是否用到了索引,结果只有第一个使用到
EXPLAIN select * from test where f1=1;
EXPLAIN select * from test where f2=1;
EXPLAIN select * from test where f3=1;
#使用第一个字段查询,是否使用到索引,结果都能使用到索引
EXPLAIN select * from test where f1=1;
EXPLAIN select * from test where f1=1 and f2=1;
EXPLAIN select * from test where f1=1 and f3=1;
EXPLAIN select * from test where f1=1 and f2=1 and f3=1;
#不使用第一个字段,是否使用到索引,结果都不能使用到索引
EXPLAIN select * from test where f2=1;
EXPLAIN select * from test where f2=1 and f3=1;
【总结】
1、使用相同数量的索引,顺序不影响
2、如果使用的不是全字段索引,如果没有第一个字段是拿不到索引的