mysql的联合索引使用

今天在处理数据时用到了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、如果使用的不是全字段索引,如果没有第一个字段是拿不到索引的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值