外观
创建索引
在创建数据表时创建索引
语法如下:
create table table_name(
属性名 数据类型[约束条件],
...,
[UNIQUE|FULLTEXT|SPATIAL] INDEX|KEY
[别名] (属性1[(长度)][ASC|DESC]
);INDEX和KEY参数用于指定字段索引,选择其中一个即可。
创建普通索引
create table score(
id int(11) not null auto_increment primary key,
name varchar(50) not null ,
math int(5) not null ,
chinese int(5) not null ,
english int(5) not null ,
index(id)
);
在最后一行可以看到,id已经被索引。
创建唯一索引
create table address(
id int(11) auto_increment primary key not null,
name varchar(50),
detail_address varchar(200),
unique index address(id)
);
在数据完整性约束里,若为字段设置主键约束,则MySQL会自动为该字段添加主键索引;若为字段设置候选键约束,则MySQL会自动为该字段设置唯一索引。
设置主键约束的部分语法为
constraint index_col_name primary key (col_name),其中constaint关键字表示下面的语句代表添加完整性约束,index_col_name代表主键的名称,col_name代表字段,如下面为表a中的字段a添加主键约束,由于MySQL会自动为该字段添加主键索引,因而运行结果如下图。下面是为字段b添加候选键约束的演示。
运行结果
创建全文索引
create table cards(
id int(11) auto_increment primary key not null,
name varchar(50),
number bigint(11),
info varchar(50),
fulltext key card_info(info)
)
创建单列索引
create table telephone(
id int(11) primary key auto_increment not null,
name varchar(50) not null,
tel varchar(50) not null,
index tel_num(tel(20))
);
创建多列索引
create table information(
id int(11) auto_increment primary key not null,
name varchar(50) not null,
sex varchar(5) not null,
birthday varchar(50) not null,
index info(name,sex)
);
创建空间索引
create table list(
id int(11) primary key auto_increment not null,
goods geometry not null,
spatial index listinfo(goods)
);
在已建立的数据表上创建索引
语法结构如下:
CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name ON table_name(属性 [(length)])[ASC|DESC]);创建普通索引
在创建普通索引之前,先来看一下student的表的结构。

create index id_index on student(id);
创建唯一索引
语法:
CREATE UNIQUE INDEX 索引名 ON 数据表名称(字段名称);我们在删除前面创建的索引之后为id添加一个唯一索引(删除索引的语句没有包含在下面的截图中):
create unique index id_uindex on student(id);
创建全文索引
语法如下:
CREATE FULLTEXT INDEX 索引名 ON 数据表名称(字段名称);我们在演示之前先创建一个如下的数据表:

create fulltext index info_index on information(info);
创建单列索引
语法如下:
CREATE INDEX 索引名 ON 数据表名称(字段名称(长度));设置字段名称长度,可以优化查询,提高查询效率。
我们为info中的information添加单列索引(先删除):
create index info_index on information(info(10));
创建多列索引
语法如下:
CREATE INDEX 索引名 ON 数据表名称(字段1,...);如我们为数据表student添加一个多列索引:
create index multi_index on student(name,age);
创建空间索引
语法如下:
CREATE SPATIAL INDEX 索引名 ON 数据表名称(字段名称);
