【建表語句】
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;
問題:我們創建了復合索引idx_test03_c1234 ,根據以下SQL分析下索引使用情況?
1 explain select * from test03 where c1='a1'; 2 explain select * from test03 where c1='a1' and c2='a2'; 3 explain select * from test03 where c1='a1' and c2='a2' and c3='a3'; 4 explain select * from test03 where c1='a1' and c2='a2' and c3='a3' and c4='a4';
1)
explain select * from test03 where c1='a1' and c2='a2' and c3='a3' and c4='a4';

2)
explain select * from test03 where c1='a1' and c2='a2' and c4='a4' and c3='a3';

explain select * from test03 where c4='a4' and c3='a3' and c2='a2' and c1='a1';

3)
explain select * from test03 where 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' and c3='a3';

說明:4個索引全部使用,雖然c3在最后,但是mysql可以自動調優。
5)
explain select * from test03 where c1='a1' and c2='a2' and c4='a4' order by c3;
c3作用在排序而不是查找

【索引的兩大功能:查找和排序】
6)
explain select * from test03 where c1='a1' and c2='a2' order by c3;

7)
explain select * from test03 where c1='a1' and c2='a2' order by c4;
出現了filesort

8)
8.1
explain select * from test03 where c1='a1' and c5='a5' order by c2,c3;

只用c1一個字段索引,但是c2、c3用於排序,無filesort
8.2
explain select * from test03 where c1='a1' and c5='a5' order by c3,c2;

出現了filesort,我們建的索引是1234,它沒有按照順序來,3 2 顛倒了
9)
explain select * from test03 where c1='a1' and c2='a2' order by c2,c3;

10)
explain select * from test03 where c1='a1' and c2='a2' and c5='a5' order by c2,c3;

用c1、c2兩個字段索引,但是c2、c3用於排序,無filesort
explain select * from test03 where c1='a1' and c2='a2' and c5='a5' order by c3,c2;

本例有常量c2的情況,和8.2對比(c2='c2'已經有具體值,為常量時,無需排序)
explain select * from test03 where c1='a1' and c5='a5' order by c3,c2;

filesort出現
11)
explain select * from test03 where c1='a1' and c4='a4' group by c2,c3;

12)
explain select * from test03 where c1='a1' and c4='a4' group by c3,c2;

Using where; Using temporary; Using filesort
【group by表面理解為分組,但是要注意的是,分組之前必排序】
【結論】

【一般性建議】
1、對於單鍵索引,盡量選擇針對當前query過濾性更好的索引
2、在選擇組合索引的時候,當前Query中過濾性最好的字段在索引字段順序中,位置越靠前(左)越好。(避免索引過濾性好的索引失效)
3、在選擇組合索引的時候,盡量選擇可以能夠包含當前query中的where字句中更多字段的索引
4、盡可能通過分析統計信息和調整query的寫法來達到選擇合適索引的目的
