索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构。类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获取即可。

以 B-tree 形式存储

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
1                     30
2  
3         10                        40
4  
5    5         15            35             66
6  
7 1   6     11    19      21      39     55     100

MySQL中常见索引有:

  • 普通索引
  • 唯一索引
  • 主键索引
  • 组合索引

1、普通索引

普通索引仅有一个功能:加速查询

MySQL---索引 Mysql 第1张
1 create table in1( 2     nid int not null auto_increment primary key, 3     name varchar(32) not null, 4     email varchar(64) not null, 5  extra text, 6  index ix_name (name) 7 )
创建表 + 索引 MySQL---索引 Mysql 第3张
1 create index index_name on table_name(column_name)
创建索引 MySQL---索引 Mysql 第5张
1 drop index_name on table_name;
删除索引 MySQL---索引 Mysql 第7张
1 show index from table_name;
查看索引

注意:对于创建索引时如果是BLOB 和 TEXT 类型,必须指定length。

MySQL---索引 Mysql 第9张
1 create index ix_extra on in1(extra(32));
View Code

2、唯一索引

唯一索引有两个功能:加速查询 和 唯一约束(可含null)

MySQL---索引 Mysql 第11张
1 create table in1( 2     nid int not null auto_increment primary key, 3     name varchar(32) not null, 4     email varchar(64) not null, 5  extra text, 6  unique ix_name (name) 7 )
创建表 + 唯一索引 MySQL---索引 Mysql 第13张
1 create unique index 索引名 on 表名(列名);
创建唯一索引 MySQL---索引 Mysql 第15张
1 drop unique index 索引名 on 表名;
删除唯一索引

3、主键索引

主键有两个功能:加速查询 和 唯一约束(不可含null)

MySQL---索引 Mysql 第17张
 1 create table in1(  2     nid int not null auto_increment primary key,  3     name varchar(32) not null,  4     email varchar(64) not null,  5  extra text,  6  index ix_name (name)  7 )  8 
 9 OR 10 
11 create table in1( 12     nid int not null auto_increment, 13     name varchar(32) not null, 14     email varchar(64) not null, 15  extra text, 16  primary key(ni1), 17  index ix_name (name) 18 )
创建表 + 创建主键 MySQL---索引 Mysql 第19张
1 alter table 表名 add primary key(列名);
创建主键 MySQL---索引 Mysql 第21张
1 alter table 表名 drop primary key; 2 alter table 表名  modify  列名 int, drop primary key;
删除主键

4、组合索引

组合索引是将n个列组合成一个索引

其应用场景为:频繁的同时使用n列来进行查询,如:where n1 = 'alex' and n2 = 666。

MySQL---索引 Mysql 第23张
1 create table in3( 2     nid int not null auto_increment primary key, 3     name varchar(32) not null, 4     email varchar(64) not null, 5  extra text 6 )
创建表 MySQL---索引 Mysql 第25张
1 create index ix_name_email on in3(name,email);
创建组合索引

如上创建组合索引之后,查询(最左前缀):

  • name and email  -- 使用索引
  • name                 -- 使用索引
  • email                 -- 不使用索引

注意:对于同时搜索n个条件时,组合索引的性能好于多个单一索引合并。

补充

1、覆盖索引

select * from tb where nid=1; # 先去索引中找 # 再去数据中找
 select nid from tb where nid<10; # 先去索引中找(只需要在索引表中就能获取到数据) # 该情况应用上索引,并且不用去数据表中操作,即覆盖索引

2、合并索引(根据业务需求决定)

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄