不同的数据存储在磁盘上的不同结构, 我们可以通过存储引擎来进行区分, 但是当数据存储到文件中, 我们通过什么样的数据结构, 可以让我们快速的从数据库中查询到对应的数据

那么对于MySQL数据库, 我们也可以使用索引来进行帮助我们快速查找需要的数据.
索引是对数据库表中一列或多列的值进行排序的一种结构,使用索引可快速访问数据库表中的特定信息。
MySQL官方对索引的定义为:索引(Index)是帮助MySQL高效获取数据的数据结构。
在数据之外,数据库系统还维护着满足特定查找算法的数据结构,这些数据结构以某种方式引用(指向)数据,这样就可以在这些数据结构上实现高级查找算法。这种数据结构,就是索引。
为什么需要使用索引
我们创建两个表t21和t22, 其中的表的结构是一样, 数据是一样, 但是对于t22 有创建一个查询字段的索引, 我们来比较一下两个SQL语句的性能
-- 演示有索引查询和没有索引查询的操作create table t21(id int not null auto_increment PRIMARY key ,name varchar(20),age int)-- 创建一个存储过程, 模拟插入1000000数据create procedure idata2()begindeclare i int;set i=1;while(i<=1000000)doinsert into t21(name,age) values(CONCAT('maoge',i), floor(16+rand()*40));set i=i+1;end while;end;;call idata2();create table t22 as select * from t21;-- 给表t22添加一个索引alter table t22 add key idx_name (name);-- 进行性能比较select id, name,age from t21 where name ='maoge400000';select id,name,age from t22 where name ='maoge400000';show profiles;
索引的分类
常见的索引有 主键索引, 唯一索引, 普通索引
- 主键索引: 每个表有也只有一个主键索引, 强烈建议在创建表的时候指定主键索引, 如果没有指定主键索引, 对于表会默认生成一个非空且唯一的主键索引
- 唯一索引:可以为空, 但是不能重复, 必须唯一. 一个表可以有多个唯一索引
- 普通索引: 可以为空, 可以重复, 如果普通索引可以满足对应的业务需求, 推荐使用普通索引
索引的基本操作
创建索引
创建主键索引
create table t1( id int (11) not null, name varchar(12), primary key (id) )创建唯一索引
其中 name 就是一个唯一索引, 通过使用 unique key 来指定唯一索引, idx_name 是索引名称create table t2( id int (11) not null, name varchar(12), primary key (id), unique key idx_name(name) )
如果索引名称没有指定, 或默认使用列名作为索引名称创建普通索引
其中 name 就是一个普通索引, 通过使用 key 来指定唯一索引, idx_name 是索引名称create table t3( id int (11) not null, name varchar(12), primary key (id), key idx_name (name) ) engine=innodb添加索引
如果一个表已经创建完成, 我们需要对这个已经拥有数据的表添加索引, 我们可以通过命令或者通过工具进行索引添加-- 创建t4 表, 主键id create table t4( id int(11) not null, name varchar(12), sn varchar(12), score int(6) ); -- 给id 添加一个主键索引 alter table t4 add primary key (id); -- 给name添加一个唯一索引 alter table t4 add unique key idx_name (name); -- 给score 添加一个普通索引 alter table t4 add key idx_score (score); show index from t4;删除索引
-- 删除主键索引 id alter table t4 drop primary key; -- 删除唯一索引 name alter table t4 drop index idx_name -- 删除普通索引 score alter table t4 drop index idx_score复合索引
有时候我们在创建索引的时候,可能不只有一个列,需要把多个列同时创建一个索引的情况, 我们称之为复合索引
具体语法可以参考官方文档: https://dev.mysql.com/doc/refman/8.0/en/alter-table.html-- 复合索引 name, sn 创建一个唯一索引 -- 对于复合索引(联合索引) 索引是有顺序的 alter table t4 add unique key idx_name_sn (name, sn) show index from t4; -- 删除复合索引 alter table t4 drop key idx_name_sn show index from t4;
除了删除使用命令的方式创建, 我们也可以使用对应的可视化工具进行创建, 比如下面是Navicat的截图
