一、簡介
索引是一個單獨的、存儲在磁盤上的數據庫結構,包含對數據表裏所有記錄的引用指針。使用索引可快速找出在某個或多個列中有一特定值的行。
二、優缺點
優點:
1.大大加快數據的查詢速度
2.唯一索引可以保證數據庫表每一行的唯一性
3.加速表連接時間
缺點:
1.創建、維護索引要耗費時間
2.索引需佔磁盤空間
3.對錶進行更新操作時,索引也要動態維護,降低了維護速度
三、類別
1.普通索引和唯一索引
2.單列索引和多列索引
3.全文索引
4.空間索引
注意:MySQL中只有MyISAM存儲引擎支持全文索引和空間索引
四、設計原則
1.索引並非越多越好
2.對經常用於查詢的列創建索引,避免對經常更新的列創建過多索引
3.在不同值較多的列建立索引
4.在頻繁進行排序或分組的列上建立索引
五、創建索引
1.普通索引:
create table book (
bookid int not null,
bookname varchar(255) not null,
index booknameindex(bookname)
);
2.唯一索引
create table book (
bookid int not null,
bookname varchar(255) not null,
unique index bookidindex(bookid)
);
3.組合索引
create table book (
bookid int not null,
bookname varchar(255) not null,
index multiindex(bookid,bookname)
);
4.已存在表加索引
create index booknameindex on book(bookname)
或
alter table book add index booknameindex(bookname)
六、刪除索引
drop index booknameindex on book