本文目录结构:
1、创建索引
(1)在创建表的时候同时创建索引
(2)表创建成功后,增加索引
(3)修改表的方式,增加索引
2、查看索引
3、删除索引
文章《MySQL索引详解(一)索引的分类》中介绍了各种索引的类型
下面介绍一下各种索引的使用方法
1、创建索引
(1)在创建表的时候同时创建索引
普通索引
create table person(
id int not null,
name varchar(64) not null,
address varchar(64) not null,
phone_number varchar(64) not null,
index(name)
);
唯一索引
create table person_unique(
id int not null,
name varchar(64) not null,
address varchar(64) not null,
phone_number varchar(64) not null,
unique index name_index(name)
);
主键索引
create table person_primary(
id int primary key auto_increment,
name varchar(64) not null,
address varchar(64) not null,
phone_number varchar(64) not null
);
组合索引
create table person_com(
id int not null,
name varchar(64) not null,
address varchar(64) not null,
phone_number varchar(64) not null,
key com_index(name,address)
);
全文索引
create table person_fulltext(
id int not null,
name varchar(64) not null,
address varchar(64) not null,
phone_number varchar(64) not null,
fulltext index fulltext_index(name)
);
(2)表创建成功后,增加索引
普通索引
create index index_name on person(name);
唯一索引
create unique index unique_index_name on person(name);
组合索引
create index com_index on person(name,address);
全文索引
create fulltext index fulltext_index_name on person(name);
(3)修改表的方式,增加索引
普通索引
alter table person add index index_address(address);
唯一索引
alter table person add unique index unique_index_address(address);
组合索引
alter table person add index com_index_id_address(id,address);
全文索引
alter table person add fulltext index fulltext_index_address(address);
2、查看索引
命令:
show index from person;
返回结果:
![](https://img.haomeiwen.com/i3408605/8ce3ca28c7532ada.png)
Non_unique:如果索引中字段可重复则为1,不可重复为0
Key_name:索引名称,如果是主键索引,此项固定为PRIMARY
Seq_in_index:索引属于第几列
Column_name:列的名称
Collation:列以什么方式存储在索引中,A表示升序,NULL表示无序
Cardinality:索引中唯一值的数目的估计值。通过运行ANALYZE TABLE或myisamchk -a可以更新。基数根据被存储为整数的统计数据来计数,所以即使对于小型表,该值也没有必要是精确的。基数越大,当进行联合时,MySQL使用该索引的机 会就越大
Sub_part:如果列被部分的编入索引,则为被编入的字符数,如果整列当做索引,则为null
Packet:是否被压缩,没有则为null
Null:如果列中值有null,则为Yes,否则为No
Index_type:索引类型,有四类(BTREE, FULLTEXT, HASH, RTREE),以上单列、组合索引都是BTREE,全文索引为FULLTEXT
Comment:列的comment
Index_comment:索引的comment
3、删除索引
(1)、使用alter table删除索引
命令:
alter table person drop index name;
单列索引,组合索引,全文索引的删除方式相同。注意删除主键索引时,需要先删除auto_increment,然后再删除主键primary key。
(2)、使用drop index删除索引
命令:
drop index index_name on person;
参考资料
1、《MySQL性能调优与架构设计》
2、https://blog.csdn.net/superdangbo/article/details/79283752
3、https://www.cnblogs.com/shihaiming/p/8529502.html
4、https://blog.csdn.net/qq_41573234/article/details/80328281
网友评论