sql中索引優化查詢效率的總結

在數據庫中,對字段建立索引可以大大提高查詢速度。
創建一個測試表testtb,並且向表中插入30萬條記錄。
create table testtb(id int not null, name varchar(10) not null, age int not null);

查看錶中索引的方法:
show index from testtb;
show keys from testtb;

創建普通索引:
create index id_index on testtb(id);
alter table testtb add index id_index (id);
create table testtb(id int not null, name varchar(10) not null, age int not null, index id_index (id));

創建unique索引:
create unique index id_index on testtb(id);
alter table testtb add unique id_index(id);
create table testtb(id int not null, name varchar(10) not null, age int not null, unique index id_index (id));

創建primary key索引:
alter table testtb add primary key (id);
create table testtb(id int not null primary key , name varchar(10) not null, age int not null);

刪除索引的方法:
drop index id_index on testtb;
alter table testtb drop index id_index;

刪除primary key索引:
alter table testtb drop primary key;

一:無索引情況下
在沒有建立索引的時候,查詢記錄語句explain select * from testtb where id = 200000;此時受影響的行有300000行,需要掃描全部記錄。
這裏寫圖片描述

二:創建普通索引
創建普通索引的情況下:
create index id_index on testtb(id);
再次使用查詢記錄語句,此時受影響的行只有1行,不需要掃描,即可找到該記錄。
這裏寫圖片描述

三:唯一索引
索引列的值必須唯一,不允許有空值。如果是組合索引,則組合的列值必須是唯一的。

四:組合索引
create index id_name_index on testtb(id,name);
如果分別在id, name上建立單列索引,查詢時和組合索引相比,效率也會不大一樣,mysql只會用到其中的一個認爲最有效的單列索引。

建立組合索引(id, name)相當於建立了(id,name), (id)兩種索引。索引組合是從最左面開始組合的(所以沒有(name)這個索引)。
此時使用以下語句會用到聯合索引,提高查詢效率
explain select * from testtb where id=200000 and name =’kobe200000’;
這裏寫圖片描述

explain select * from testtb where id=200000;
這裏寫圖片描述

使用單獨查詢name時不會用到聯合索引,
explain select * from testtb where name =’kobe200000’;
這裏寫圖片描述

五:建立索引的選擇
一般在where和join中出現的列需要建立索引。
Mysql只對<,>,<=,>=,=,between,in以及某些時候的like這些情況下使用索引。
使用like的情況:
在以通配符%和_開頭查詢時,mysql不會使用索引。

六:索引的缺點
1:索引會降低更新表的速度,如果對錶進行Insert,update和delete操作,需要更新表,此時,Mysql不僅需要保存數據,還需要保存一下索引文件。
2:建立索引會佔用磁盤空間的索引文件。如果在一個大表上創建多個組合索引,會導致索引文件很大。
不能濫用索引,儘量建立最優的索引組合。

七:注意事項:
1:索引不會包含有NULL值的列
只要列中包含有NULL值都將不會被包含在索引中,複合索引中只要有一列含有NULL值,那麼這一列對於此複合索引就是無效的。所以我們在數據庫設計時不要讓字段的默認值爲NULL。
2:使用短索引
對串列進行索引,如果可能應該指定一個前綴長度。例如,如果有一個CHAR(255)的列,如果在前10個或20個字符內,多數值是惟一的,那麼就不要對整個列進行索引。短索引不僅可以提高查詢速度而且可以節省磁盤空間和I/O操作。
3:索引列排序
MySQL查詢只使用一個索引,因此如果where子句中已經使用了索引的話,那麼order by中的列是不會使用索引的。因此數據庫默認排序可以符合要求的情況下不要使用排序操作;儘量不要包含多個列的排序,如果需要最好給這些列創建複合索引。
4:like語句操作
一般情況下不鼓勵使用like操作,如果非使用不可,如何使用也是一個問題。like “%aaa%” 不會使用索引而like “aaa%”可以使用索引。
5:不要在列上進行運算
select * from users where YEAR(adddate)<2007;
將在每個行上進行運算,這將導致索引失效而進行全表掃描,因此我們可以改成:
select * from users where adddate<‘2007-01-01’;
6:不使用NOT IN和<>操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章