创建索引
创建索引的方式有直接创建、修改表添加和创建时直接创建三种。
1、直接创建
CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name ON table_name (column(length),…) [ASC|DESC]
– 普通索引
create index bknameIndex on book(bookname) ;
– 唯一索引
create unique index unique_Index on book(bookId) ;
–单列索引
create index single_Index on book(comment(10)) ;
– 多列索引
create index mutil_Index on book(authors(20) , info(20)) ;
–全文索引
create fulltext index fulltext_Index on book(info) ;
2、修改表添加
ALTER TABLE table_name ADD [UNIQUE|FULLTEXT|SPATIAL] [INDEX|KEY] index_name (column(length),…) [ASC|DESC]
– 普通索引
alter table book add index bkName(bookname(30)) ;
–唯一索引
alter table book add unique index uniqueIndex(bookId) ;
–单列索引
alter table book add index signalIndex2 on(comment(50)) ;
–多列索引
alter table book add index mutilIndex (authors(30) , info(50)) ;
–创建全文索引
alter table book add fulltext index fulltextIndex (info) ;
3、创建时直接创建
CREATE TABLE table_name (
……(创建字段和约束),
[UNIQUE|FULLTEXT|SPATIAL] [INDEX|KEY] [INDEX|KEY] [index_name] (col_name [length]) [ASC|DESC]
)
– 普通索引
create table book(
……
index pub_index(year_publication)
);
– 唯一索引
create table book(
……
unique index pub_index(bookid)
);
– 单列索引
create table book(
……
index single_index(authors)
);
– 多列索引
create table book(
……
index mutil_index(bookid, authors)
);
– 全文索引,需要修改表的存储引擎为MyISAM
create table book(
……
fulltext index fulltext_index(info)
);
4、删除索引
(1)使用ALTER TABLE删除索引
ALTER TABLE table_name DROP INDEX index_name ;
有AUTO_INCREMENT约束的字段的唯一索引不能被删除
删除book表中名为fulltext_Index的索引alter table book drop index fulltext_Index ;
(2)使用DROP INDEX删除索引
DROP INDEX index_name ON table_name ;
删除book表中名为fulltext_Index的索引drop index mutil_index on book ;