create table test03(
id int primary key not null auto_increment,
c1 char(10),
c2 char(10),
c3 char(10),
c4 char(10),
c5 char(10)
);
insert into test03(c1,c2,c3,c4,c5) values('a1','a2','a3','a4','a5');
insert into test03(c1,c2,c3,c4,c5) values('b1','b2','b3','b4','b5');
insert into test03(c1,c2,c3,c4,c5) values('c1','c2','c3','c4','c5');
insert into test03(c1,c2,c3,c4,c5) values('d1','d2','d3','d4','d5');
insert into test03(c1,c2,c3,c4,c5) values('e1','e2','e3','e4','e5');
select * from test03;
create index idx_test03_c1234 on test03(c1,c2,c3,c4);
show index from test03;
index.png
問題:我們創(chuàng)建了復合索引idx_test03_c1234 ,根據以下SQL分析下索引使用情況?
#使用c1索引
explain select * from test03 where c1='a1';
#使用c1 c2 索引
explain select * from test03 where c1='a1' and c2='a2';
#使用c1 c2 c3 索引
explain select * from test03 where c1='a1' and c2='a2' and c3='a3';
#使用c1 c2 c3 c4索引
explain select * from test03 where c1='a1' and c2='a2' and c3='a3' and c4='a4';
比對.png
- 案例1
explain select * from test03 where c1='a1' and c2='a2' and c4='a4' and c3='a3';
c4倒置.png
順序不一樣也能查到褪猛,因為mysql底層會自動調優(yōu)轉換赌结,假如是4321,mysql底層也會
轉化成1234吠撮,但是最好是一樣的順序尊惰。
- 案例2
explain select * from test03 where c1='a1' and c2='a2' and c3>'a3' and c4='a4';
分析結果.png
索引用于范圍查找 索引后面全失效,索引三個泥兰。
- 案例3
explain select * from test03 where c1='a1' and c2='a2' and c4>'a4' and c3='a3';
分析結果.png
變化了順序弄屡,mysql底層自動轉換,所以c1='a1' and c2='a2' and c3='a3' and c4>'a4' 所以這里是四個鞋诗。
- 案例4
explain select * from test03 where c1='a1' and c2='a2' and c4='a4' order by c3;
分析結果.png
只有兩個關聯(lián)的索引c1 c2膀捷,索引的功能是查找或者排序,c3的作用是排序不是查找削彬,但是不會被統(tǒng)計到key中担孔,key和ref中只有c1和c2江锨。
- 案例5
explain select * from test03 where c1='a1' and c2='a2' order by c3;
分析結果.png
和上面的結果一樣,說明這里和c4沒什么關系糕篇。
- 案例6
explain select * from test03 where c1='a1' and c2='a2' order by c4;
分析結果.png
這里沒有c3參與啄育,直接使用c4排序,失效拌消。
- 案例7
#順序索引排序
explain select * from test03 where c1='a1' and c5='a5' order by c2,c3;
#倒序索引排序
explain select * from test03 where c1='a1' and c5='a5' order by c3,c2;
分析結果.png
出現(xiàn)了filesort挑豌,我們建的索引是1234,它沒有按照順序來墩崩,3 2 顛倒了氓英,沒有自動轉換。
- 案例8
explain select * from test03 where c1='a1' and c2='a2' order by c2,c3;
explain select * from test03 where c1='a1' and c2='a2' and c5='a5' order by c2,c3;
explain select * from test03 where c1='a1' and c2='a2' and c5='a5' order by c3,c2;
分析結果.png
注意在案例7中鹦筹,32排序铝阐,會出現(xiàn)filesort,可是這里沒有出現(xiàn)铐拐,因為這里有c2徘键,排序字段已經是一個常量了,所以相當于roder by c3 遍蟋,一個常量order by 1吹害,有和沒有無關。
- 案例9
explain select * from test03 where c1='a1' and c4='a4' group by c2,c3;
explain select * from test03 where c1='a1' and c4='a4' group by c3,c2;
分析結果.png
group by表面上是分組虚青,實質上是排序它呀,分組之前必排序,唯一的不同group by有having
定值棒厘、范圍還是排序纵穿,一般order by是給個范圍
group by基本上需要進行排序,會有臨時表的產生奢人,為了得到數(shù)據政恍,先建一張臨時表。
5.7下达传,因為排序的順序發(fā)現(xiàn)不對篙耗,需要通過filesort,8.0下沒有宪赶。