一,最左匹配原則
如果為聯(lián)合索引 create index table on (a,b,c)
例:select * from table where a ='' and b= '' and c= ''索引是生效的
例:select * from table where a = '' and c='' 這樣只有索引a生效,索引c失效
例:select * from table where c='' 索引全部失效,不符合最左匹配法則
此聯(lián)合索引創(chuàng)建了3個索引 分別為 a索引。a,b索引代乃。a,b,c索引沸呐,他們都是一個整體醇王。所以按照最左匹配法則,a列在作為查詢條件時崭添,就能觸發(fā)索引
二寓娩,索引失效情況(引用上面的a,b,c索引)
1.(范圍查詢) select * from table where a = '' and b>'' and c='' 此時只有a,b索引生效呼渣。
2.(對列進(jìn)行運算操作) select * from table where substring(a,3,2); 索引失效
3.(數(shù)字為varchar類型不加單引號) select * from table where a=5; a為varchar類型
4.(or查詢) select * from table where a ='' or b='' 如果a列有索引棘伴,b列無索引,則整個索引失效
5.(like查詢) select * from table where a like '%1%'屁置;%在前面 索引失效焊夸,
如果非要前后都加上% ,則可使用覆蓋索引來解決
覆蓋索引: select a from table where a like '%1%'蓝角;
三淳地,盡量使用覆蓋索引 避免select * 回表查詢
1.select * from table where a ='' 走了索引,但是需要回表查詢(using index condition)
2.select a,b,c from table where a ='' 不需要回表查詢,效率更高 (覆蓋索引查詢)
四帅容,全表掃描有時比索引更快
如果表中某列大量重復(fù)出現(xiàn),sql執(zhí)行計劃會判定全表掃描比走索引效率高
五伍伤,is null,is not null有時走索引并徘,有時不走索引
如果表中null值居多, is not null走索引,反義依然
六扰魂,in走索引麦乞,Not in不走索引
七,盡量使用復(fù)合索引
create table index table on (a,b,c)等于創(chuàng)建了3個索引
a,a+b,a+b+c索引劝评。
八姐直,查看索引使用情況
show global status like 'handler_read%'