MySQL索引總結以及執行索引語句
例如:資料庫中2萬條記錄,如果要執行一個查詢,select * from table where num =1000,
如果沒有建立索引,必須要遍歷整個表,直到num=1000被找到為止,
如果在num這個列上設定索引,就不需要任何的掃描,直接在索引裡面找到1000.
所以建立索引,能夠提高資料庫的查詢速度
索引在儲存引擎中實現,因此,每種儲存引擎的索引都不一定完全相同,
並且每一種儲存引擎也不一定支援所有索引型別.
MySQL中索引的儲存型別有兩種:BTREE和HASH,具體和表的儲存引擎相關
MyISAM和InnoDB儲存引擎只支援BTREE索引,
MEMORY/HEAP儲存引擎可以支援HASH和BTREE索引
MySQL的索引分為以下幾類:
索引的設計原則:
建立索引
建立普通索引:
1.創表時建立索引
create TABLE book( bookid int not null, bookname varchar(255) not null, authors varchar(255) not null, info varchar(255) null, comment varchar(255) null, year_publication year not null, index(year_publication) )
2.創表之後,執行語句
show create table book
執行之後,可以看到book表的 year_publication 欄位成功建立了索引,索引名稱為year_publication 為MySQL自動新增
3.使用explain語句檢視索引是否在使用:
explain select * from book where year_publication=1990
執行之後:
建立唯一索引:
建立唯一索引的原因是減少查詢索引列操作的執行時間,和普通的索引相比,索引列的值必須是唯一,但允許有空值,
如果是組合索引,則列值的組合必須唯一
1.建立表
create table t1(
id int not null,
name char(30) not null,
unique index UniqIdx(id)
)
2.執行建立之後,進行查看錶結構
show create table t1
可以看到已經建立了一個名為UniqIdx的唯一索引
建立單列索引
單列索引是在資料表中的某一個欄位上建立的索引,一個表可以建立多個單列索引,上述兩個索引的建立都是屬於單列索引
1.執行創表
create table t2(
id int not null,
name char(50) null,
index SingleIdx(name(20))
)
2.執行結束後,查看錶結構:
可以看到.已經建立了名為SingleIdx的單列索引,索引長度為20
建立組合索引:
在多個欄位上建立一個索引
1.執行創表語句:
create table t3(
id int not null,
name char(30) not null,
age int not null,
info varchar(255),
index MultiIdx(id,name,age(100))
)
2.執行結束,進行查看錶結構:
show create table t3
3.同樣也能看出,id,name,age成功建立了名為MultiIdx的組合索引
建立全文索引:
FULLTEXT(全文索引)可以應用於全文搜尋,只有MyISAM儲存引擎支援FULLTEXT索引,
並且為CHAR,VARCHAR,TEXT列建立索引
1.建立表
create table t4(
id int not null,
name char(30) not null,
age int not null,
info varchar(255),
FULLTEXT INDEX FullTxtIdx(info)
)engine=MyISAM
2.查看錶結構
show create table t4
可以看到已經建立了一個FullTxtIdx的索引
全文索引適合大型資料集,對於小的資料庫來說,用處比較小
建立空間索引
必須在MyISAM型別中的表中建立,並且空間型別的欄位必須為非空!
1.創表
create table t5(
g GEOMETRY NOT NULL,
SPATIAL INDEX spatIdx(g)
)engine=MyISAM
2.查看錶結構
show create table t5
可以看到,已經建立了名為spatIdx的空間索引
需要注意的是,建立指定空間型別欄位值的非空約束.並且表的儲存引擎為MyISAM
在已經存在的表建立索引
使用ALTER TABLE 語句建立索引
1.執行語句
alter table book add index BkName(bookname(30))
2.show index 查看錶中索引
show index from book
可以看到新增了一個索引
建立唯一索引:
alter table book add index UniqiIdx(bookId)
建立單列索引:
alter table book add index BkcmtIdx(comment(50))
建立組合索引
alter table book add index BkAuandInfoIdx (authors(30),info(50))
建立全文索引:
alter table t6 add FULLTEXT infoFTIdx (info)
建立空間索引:
alter table t7 add spatial index spatIdx(g)
使用CREATE TABLE 語句建立索引
建立普通索引:
create index BkNameIdx on book(bookname)
建立唯一索引:
create unique index UniqIdx on book(bookId)
建立單列索引:
create index BKcmtIdx on book(comment(50))
建立組合索引:
create index BkAuAndInfoIdx on book(authors(20),info(50))
建立全文索引
create fulltext index on book (info)
建立空間索引:
create spatial index spatIdx on book(g)
刪除索引
使用ALTER TABLE 語句刪除索引
alter table 表名 drop index 索引名
使用DROP INDEX 語句刪除索引
drop index 索引名 on 表名
才疏學淺,只能總結到這些基礎的,歡迎交流