create table book(bookid int not null,bookname varchar(255) not null,author varchar(255) not null,info varchar(255),comment varchar(255),year_publication year not null,index (year_publication)//index/key(列名));
show create table book;
explain select * from book where year_publication=1990;//使用explain查看索引是否正在使用,重点观察结果中的possible keys和key的值,此处都为year_publication,说明执行此查询语句时使用了索引
(2)唯一索引
create table t1(id int not null,name char(30) not null,unique index udid(id)//unique index 索引名(列名)//索引名可省略,默认名可show create table 展示);
show create table t1;
(3)组合索引
create table t3(id int not null,name char(30) not null,age int not null,info varchar(255),index (id,name,age));
explain select * from t3 where id=1 and name='joy';explain select * from t3 where name='joy';//查询时,必须遵从最左索引前缀原则
(4)全文索引 ,只为字符(char,varchar,text)索引
create table t4(id int not null,name char(30),age int not null,info varchar(255),fulltext index (info));
show create table t4;
(5)空间索引(ENGIN=MyISAM)
create table t5(g geometry not null,spatial index(g)//只能对一些图形等使用);
2、在已经存在的表上创建索引
(1)使用alter table
alter table 表名 add index【索引名】(列名);//索引名可以省略,默认为列名alter table book add index(bookname);//查询索引show index from 表名;
(2)使用create index
create index [索引名] on 表名(列名);
二、删除索引
1、使用alter table
alter table 表名 drop index 索引名; alter table book drop index id;
2、使用drop index
drop index 索引名 on 表名; drop index bookname on book;