使用索引注意事项
?
索引的注意事項
創(chuàng)建一張表
?新增dept 數(shù)據(jù)
create PROCEDURE insert_dept(in start int(10),in max_num int(10)) BEGINdeclare i int DEFAULT 0;set autocommit=0;REPEATset i=i+1;insert into dept values ((start+i),rand_string(10),rand_string(8));UNTIL i =max_numend REPEAT;commit; END 執(zhí)行 call insert_dept(100,10);創(chuàng)建主鍵索引
alter table 表名 add primary key (列名);
創(chuàng)建一個聯(lián)合索引
alter table dept add index my_ind (dname,loc); //? dname 左邊的列,loc就是右邊的列
注意:
1.對于創(chuàng)建的多列索引,如果不是使用第一部分,則不會創(chuàng)建索引。
explain select * from dept where loc='aaa'\G
就不會使用到索引
2.模糊查詢在like前面有百分號開頭會失效。
3. 如果條件中有or,即使其中有條件帶索引也不會使用。換言之,就是要求使用的所有字段,都必須建立索引, 我們建議大家盡量避免使用or 關(guān)鍵字
4.如果列類型是字符串,那一定要在條件中將數(shù)據(jù)使用引號引用起來。否則不使用索引。(添加時,字符串必須’’), 也就是,如果列是字符串類型,就一定要用 ‘’ 把他包括起來.
5.如果mysql估計使用全表掃描要比使用索引快,則不使用索引。
?
?
查詢所用使用率
show status like ‘handler_read%’;
?
大家可以注意:
handler_read_key:這個值越高越好,越高表示使用索引查詢到的次數(shù)。
handler_read_rnd_next:這個值越高,說明查詢低效。
總結(jié)