create table book( bookid int not null, bookname varchar(255) not null, authors varchar(255) not null, year_publication year not null, index (year_publication) -- 创建普通索引 );
创建唯一索引
1 2 3 4 5
create table t1( id int not null, name char(30) not null, unique index UniqIdx (id) -- 创建唯一索引 );
创建单列索引
1 2 3 4 5
create table t2( id int not null, name char(50) null, index SingIdx (name(20)) -- 创建单列索引 );
创建组合索引
1 2 3 4 5 6 7
create table t3( id int not null, name char(30) not null, age int not null, info varchar(255), index MultiIdx (id, name, age) -- 创建多列索引 -- 查询时需遵循“最左前缀”原则 );
后期创建
在已存在的表中创建索引
两种方法:
使用Alter Table语句创建
使用Create Index语句创建
使用ALter Table创建索引
语法格式:
1
alter table <表名> add [unique|fulltext|spatial] [index|key] [索引名] (字段名[长度],...) [asc|desc]
使用Create Index创建索引
语法格式:
1
create [unique|fulltext|spatial] index <索引名> on <表名> (字段名[长度],...) [asc|desc]
组合索引的“左前缀”原则
查询顺序遵循最左前缀的情况
1
explain select * from t3 where id = 1 and name = 'joe';
01
查询顺序不遵循左前缀的情况
1
explain select * from t3 where name = 'joe' and age = 1;