目录
索引的概念
索引的分类
创建索引
删除索引
索引是对数据库表中的一列或多列的值进行排序后的一种结构,能够提高查询速度。
-
索引的分类
分类 | 解释 |
---|
普通索引 | 由KEY或者INDEX定义,是MySql中的基本索引类型,可以创建在任何数据类型中, 其值是否唯一由约束条件决定 |
---|
唯一索引 | 由UNIQUE 定义的索引,该索引所在的字段的值必须唯一 |
---|
全文索引 | 由FULLEXT定义的索引,它只能创建在CHAR、VARCHAR、或者TEXT类型的字段上 现在只有MyISAM支持全文索引 |
---|
单列索引 | 指的是在表中的单个字段上创建索引,它可以是普通索引、唯一索引或者全文索引, 只要保证该索引只对应表中的一个字段即可 |
---|
多列索引 | 指在表中的多个字段创建索引,只有在查询条件中使用了这些字段中的第一个字段时, 该索引才会被使用。 |
---|
空间索引 | 由SPACIAL定义的索引,它只能穿建在空间数据类型的字段上。创建空间索引的字段, 必须声明为NOT NULL。 |
---|
-
创建索引
方法 | 解释 |
---|
创建表的时候创建索引 | create table 表名 (字段名 数据类型 [约束],
字段名 数据类型 [约束],
...
字段名 数据类型 [UNIQUE|FULLTEXT|SPATIAL] INDEX|KEY [别名] (字段名1[长度] [ASC|DESC]);
- UNIQUE:可选参数,表示唯一索引
- FULLTEXT:可选参数,表示全文索引
- SPATIAL:可选参数,表示空间索引
- INDEX和KEY:二选一,用来表示字段的索引
- 别名:可选参数,表示创建的索引的名称
- 字段名1:指定索引对于字段的名称
- 长度:可选参数,用于表示索引的长度
- ASC和DESC:可选参数,分别表示升序和降序
|
---|
在已存在的表上创建索引 | alter table 表名 add [UNIQUE|FULLTEXT|SPATIAL] INDEX 索引名称 (字段名[(长度)] [ASC|DESC]); |
---|
方法 | 举例 |
---|
创建表的时候创建索引 |
- 创建普通索引
create table b1 (
id int,
name varchar(20),
score float,
index(id)); - 创建唯一索引
create table b2 (
id int not null,
name varchar(20) not null,
score float,
unique index bieming(id ASC)); - 创建全文索引
create table b3 (
id int not null,
name varchar(20) not null,
score float,
fulltext index bieming(name)); - 创建单列索引
create table b4 (
id int not null,
name varchar(20) not null,
score float,
index danliebieming(name(20))); - 创建多列索引
create table b5 (
id int not null,
name varchar(20) not null,
score float,
index multi (id,name(20))); - 创建空间索引
create table b6 (
id int,
space geometry not null,
spatial index sp(space))ENGINE=MyISAM; 查看索引是否被使用 explain select * from b1 where id=1 \G;
|
---|
在已存在的表上创建索引 | create table b1(
id int(20) not null,
name varchar(255) not null,
grade float) create table b2 (
bookid int not null,
bookname varchar(255) not null,
content varchar(255) null)ENGINE=MyISAM; create table b3 (
g geometry not null)ENGINE=MyISAM;
- 创建普通索引
create index putongsy on b1(id); - 创建唯一索引
crate unique index weiyisy on b1(id); - 创建单列索引
create index danliesy on b1(id); - 常见多列索引
create index duoliesy on b1(id,name); - 创建全文索引
create fulltext index quanwensy on b2(content); - 创建空间索引
create spatial index kongjiansy on b3(g);
|
---|
-
删除索引
方法 | 举例 |
---|
使用ALTER TABLE删除索引 | alter table 表名 drop index 索引名; |
---|
使用DROP INDEX 删除索引 | drop index 索引名 on 表名; |
---|