Mysql多列索引经典案例

一个经典的多列索引案例,如题:

假设某个表有一个联合索引(c1,c2,c3,c4)一下——只能使用该联合索引的 c1,c2,c3 部分
Awhere c1=x and c2=x and c4>x and c3=x
B where c1=x and c2=x and c4=x order by c3
C where c1=x and c4= x group by c3,c2
D where c1=x and c5=x order by c2,c3
E where c1=x and c2=x and c5=? order by c2,c3

创建一张测试表

create table test (
    c1 tinyint(1) not null default 0,
    c2 tinyint(1) not null default 0,
    c3 tinyint(1) not null default 0,
    c4 tinyint(1) not null default 0,
    c5 tinyint(1) not null default 0,
    index c1234(c1,c2,c3,c4)
);
//插入两条数据
insert into test values (1,3,5,6,7),(2,3,9,8,3),(4,3,2,7,5);
insert into test values (2,4,5,8,7),(1,3,5,8,4),(3,4,2,9,6);

分析A => c1=x and c2=x and c4>x and c3=x <==等价==> c1=x and c2=x and c3=x and c4>x
c1,c2,c3,c4 都能用上

737276-20171215223309808-224869015.png

737276-20171215223338543-996884371.png


分析B => select * from test where c1=1 and c2=2 and c4=3 order by c3
c1 ,c2 索引用上了,在 c2 用到索引的基础上,c3 是排好序的,因此不用额外排序,而 c4 没发挥作用

737276-20171215223920371-1770564499.png


分析C => select * from test where c1=1 and c4=2 group by c3,c2
只用到 c1 索引,因为 group by c3,c2 的顺序无法利用 c2,c3 索引

737276-20171215224122668-718396357.png


分析D => select * from test where c1=1 and c5=2 order by c2,c3
C1 确定的基础上,c2 是有序的,C2 之下 C3 是有序的,因此 c2,c3 发挥的排序的作用. 因此,没用到 filesort

737276-20171215224339246-49181886.png


分析E => select * from test where c1=1 and c2=3 and c5=2 order by c3;
因为 c2 的值既是固定的,参与排序时并不考虑

737276-20171215224611215-542547524.png

转载于:https://www.cnblogs.com/yxhblogs/p/8045106.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值