day16:索引

索引:索引是内部表结构,MySQL用它基于索引列的值来提供对表中记录的快速访问.它缩短了MySQL服务器搜索查询将返回记录所用的时间,从而提高了MySQL服务器的效率。

MySQL支持以下类型的索引:

主键:此索引要求定义了该索引的列必须为表中的所用记录中的唯一值。并且,不能为null。

外键:此索引在事务表中引用主表列的引用列上定义,以定义这些表之间的关系,确保这些表存储的数据的一致性。

唯一:此索引在包含表中记录的唯一值的列上定义,但可以包含null值。

常规:此索引在可以包含表中的重复值和null值的列上定义。

全文:此索引在可以接受字符串值的列上定义。此索引的目的是提高搜索列数据中所包含字符串的速度。可以定义全文索引的列的数据类型可以为char、varchar或text.而且,这些列可以接收重复值或null值。

一、创建索引:

1、创建常规索引语法

create  table  表名{

字段名  字段类型(字段长度) 约束,

...

字段名  字段类型(字段长度) 约束,

index  索引名(字段名)

}

例如:在创建demo1表时给dname添加普通索引

create table demo1(
did int primary key,
dname varchar(55) not null,
dage int not null,
index dname_index(dname)
);

2、创建全文索引语法

create  table  表名{

字段名  字段类型(字段长度) 约束,

...

字段名  字段类型(字段长度) 约束,

fulltext  索引名(字段名)

}

例如:在创建demo2表时给dname添加全文索引

create table demo2(
did int primary key,
dname varchar(55) not null,
dage int not null,
FULLTEXT dname_FULLTEXT(dname)
);

二、查看索引:

show  index  from  表名;

例如:查看demo1上的索引

show index from demo1;

查看demo2上的索引

show index from demo2;

三、在现有表上添加索引

alert  table  表名   add  index  索引名 (字段名)

例如:在demo1上添加常规索引

alter table demo1 add index dage_index(dage);

create  index  索引名  on   表名  (字段名)

例如:在demo2上添加常规索引

create index dage_index on demo2 (dage);

四、删除索引

1、alter  table  表名  drop  index  索引名;

例如:删除demo2上的全文索引dname_funntext

alter table demo2 drop index dname_fulltext;

2、drop  index  索引名  on  表名;

例如:删除demo2上的常规索引dage_index;

drop index dage_index on demo2;
原文地址:https://www.cnblogs.com/wuguiyu/p/11927123.html