索引的定义
官方定义:
索引(Index)是帮助MySQL高效获取数据的 数据结构。
简单理解:
简单地来说,就是 排好序的、可以快速查找的数据结构。
索引的目的 在于 提高查询效率,可以类比字典。比如查询“admin”这个单词,先定位到a,然后依次定位查找。
索引的优势
- 提高数据检索的效率,降低数据库的IO成本;
- 通过索引对数据进行排序,降低了数据库排序的成本,降低了CPU的消耗;
索引的劣势
- 索引也是一张表,该表保存了主键与索引字段,并指向实体表的记录,所以索引也是要占磁盘空间的;
- 虽然索引大大提高了查询速度,但同时也会降低更新表的速度,因为更新表的时候,MySQL不仅要保存数据,还要保存一下索引文件每次更新添加了索引列的字段,调整因为更新所带来的键值变化后的索引信息;
- 索引只是提高效率的一个因素,如果MySQL有大数据量的表,就需要花时间研究建立最优秀的索引
索引的分类
- 单值索引:一个索引只包含单个列,一个表可以有多个单列索引
- 唯一索引:索引列的值必须唯一但允许有空值
- 复合索引:一个索引可以包含多个列
创建索引
# 在创建表时创建
create table users(
id int not null primary key,
name varchar(20) null,
sex varchar(2) null,
info varchar(20) null,
index index_name(name) # 普通索引
# unique index index_name(name) # 唯一索引
# key index_id_name(id,name) # 复合索引
# fulltext index index_name(name) # 全文索引
);
# 在已建表中添加索引
create index index_name on users(name); # 普通索引
create unique index index_name on users(name); # 唯一索引
create index index_id_name on users(id,name); # 复合索引
create fulltext index index_name on users(name); # 全文索引
# 以修改表的方式添加索引
alter table users add index index_name(name); # 普通索引
alter table users add unique index index_name(name); # 唯一索引
alter table users add index index_id_name (id,name); # 复合索引
alter table users add fulltext index_name(name); # 全文索引
删除索引
drop index index_name on users;
查看索引
show index from users;