MySQL复合索引示例

-- auto-generated definition
create table test
(
    id    int      not null
        primary key,
    name  char(30) not null,
    local char(30) not null,
    age   int      null
);

create index test_name_local_age_index
    on test (name, local, age);

explain参数参考

https://blog.csdn.net/weixin_35973945/article/details/124128677https://blog.csdn.net/weixin_35973945/article/details/124128677

ref:只会读取匹配的行,当查询的列是一个索引的最左前缀或者是一个普通索引(不是主键索引或唯一索引)会使用 ref。即仅仅会查询几行。

index: 连接类型与 all 相同,除了是扫描索引树外。主要有如下两种方式:

  • 如果查询的索引时覆盖索引,并且满足要从该表中查询的数据需求,则仅扫描索引树。在这种情况下,Extra 列为 Using index索引扫描仅仅会比 ALL 快,因为索引树通常小于整个表
  • 通过对索引的读取进行全表扫描,以按照索引顺序查找数据行,Using index 不会出现在 Extra 列。
explain select * from test where name = '1' and local = '1' and age = 1;

 符合最左匹配原则,通过explain执行结果可以看到type = ref,key使用了联合索引

explain select * from test where name = '1' and age = 1 and local = '1';

 

可以看到跟第一个执行结果一致,这是因为SQL语句经过优化器优化之后,依然符合最左匹配原则

explain select * from test where local = '1' and age = 1;

虽然不符合最左匹配原则,但是发现还是使用了索引,这是因为建表语句一共四个字段,除了主键其他的字段组成联合索引,就意味着表里面的所有数据都能在联合索引里面找到,如果增加一个字段重新执行就会发现全表扫描了。

-- auto-generated definition
create table test
(
    id     int         not null
        primary key,
    name   char(30)    not null,
    local  char(30)    not null,
    age    int         null,
    e_mail varchar(50) null
);

create index test_name_local_age_index
    on test (name, local, age);

可以看到type = ALL,extra信息里面没有using index

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值