Mysql-索引

1.什么是索引?

索引是一种将数据库中的单列或者多列的值进行排序的结构。

2.创建索引的目的?

为了优化数据库中的查询速度,用户查询数据时,系统可以不必遍历数据表中的所有记录,而是查询索引列,与一般的形式的查询相比,索引就像一本书的目录。索引会影响用户操作数据库的插入操作。因为,向有索引的表中插入记录时,数据库系统会按照索引进行排序。所以,用户可以将索引删除后,插入数据,当数据插入操作完成后,用户可以重新创建索引。

3.Mysql索引分类

 mysql的索引包括普通索引,唯一性索引,全文索引,单列索引,多列索引,空间索引等(6个)

3.1  普通索引

 普通索引,不需要应用任何限制条件的索引,该索引可以在任何数据类型中创建。字段本身的约束条件可以判断其值是否唯一或为空或者唯一。创建索引后,用户可以通过索引进行查询。

3.2 唯一性索引

 使用UNIQUE参数可以设置唯一索引。创建该索引时,索引的值必须唯一,通过唯一索引,用户可以快速定位某条记录,主键是一种特殊唯一索引。

3.3 全文检索

 使用FULLTEXT参数可以设置索引为全文索引。全文索引只能创建在CHAR,VARCHAR或者TEXT类型字段上。查询数据量较大的字符串类型的字段时,使用全文索引可以提高查询速度。

3.4 单列索引

 只对应一个字段的索引。应用该索引的条件只需要保证该索引值对应一个字段即可。

3.5 多列索引

 多列索引是在表的多个字段上创建一个索引。该索引指向创建时对应的多个字段,用户可以通过这几个字段进行查询,要想应用该索引,用户必须使用这些字段中的第一个字段。

3.6 空间索引

使用SPATIAL参数可以设置索引为空间索引。空间数据类型只能建立在空间数据类型上,这样可以提高系统获取空间数据的效率。

4.创建索引

4.1 创建普通索引

create table score(
id int(11) auto_increment primary key not null,
name varchar(50) not null,
math int(5) not null,
english int(5) not null,
chinese int(5) not null,
index(id));//index和key参数用于指定字段索引,用户在选择时选一个就可以

4.2  创建唯一性索引

create table address(
id int(11) auto_increment primary key not null,
name varchar(50) not null,
address varchar(200),
UNIQUE INDEX address(id Asc));

4.3 创建全文索引

create table cards(
id int(11) auto_increment primary key not null,
name varchar(50) not null,
number bigint(11),
info varchar(50),
FULL TEXT INDEX cards_info(info))engine=MyISAM;

4.4 创建单列索引

create table telephone(
id int(11) auto_increment primary key not null,
name varchar(50) not null,
tel varchar(50) not null,
index tel_num(tel(20)));

4.5创建多列索引  

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));

 4.6 创建空间索引

create table list(
id int(11) auto_increment primary key not null,
goods geometry not null,
SPATIAL INDEX listinfo(goods))engine=MyISAM;

5.在已建立的数据表中创建索引

5.1 创建普通索引

create index address_info on  address(id);

 5.2 创建唯一索引

create unique index address_info on  address(id);

5.3 创建全文检索

create fulltext  index address_info on  address(info);

5.4 创建单列索引

create  index address_info on  address(address(4));

5.5 创建多列索引

create  index address_info on  address(name,address);

5.6 创建空间索引

create  spatial  index address_info on  address(name);

6. 修改数据结构添加索引

6.1 添加普通索引

alter table studentinfo add index timer(time(20));

 6.2 添加唯一索引

alter table studentinfo add unique index timer(time);

6.3 添加全文索引

alter table studentinfo add fulltext index timer(info);

6.4 添加单列索引

alter table studentinfo add  index student(id(20));

6.5 添加多列索引

alter table studentinfo add  index student(username,age);

6.6 添加空间索引

alter table studentinfo add  spatial index student(username);

7.删除索引

drop index index_name on table_name;
原文地址:https://www.cnblogs.com/cainame/p/11255416.html