MySQL索引的建立对于MySQL的高效运行是很重要的,索引可以大大提高MySQL的检索速度。

一. 普通索引

作用:加速查找

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
# 1.创建表时直接创建索引
create table user(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name (name)        # ix_name 索引名,括号后面指定索引所在的列
);

# 2.创建表后再创建索引
create index ix_name on user(name);
#注意:对于创建索引时如果是BLOB 和 TEXT 类型,必须指定length,例如使用列名称的前10个字符:
create index ix_extra on user(extra(10));

# 3.删除索引
drop ix_name on user;

# 4.查看索引
show index from user;

二. 唯一索引

作用:加速查找,约束列数据不能重复,数据可以为 null

# 1.创建表时直接创建唯一索引
create table user(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    unique ix_name (name)        
);

# 2.创建表后再创建唯一索引
create  unique index ix_name on user(name);

# 3.删除唯一索引
drop unique ix_name on user;

三. 主键索引

作用:加速查找,约束列数据不能重复,数据不能为 null

# 1.创建表时直接创建主键索引
create table user(
    nid int not null auto_increment primary key,    # 指定 nid 为主键索引
    name varchar(32) not null,
    email varchar(64) not null,
    extra text      
);

# 2.创建表后添加主键索引
alter table user add primary key(nid);

# 3.删除主键索引
alter table user drop primary key;

四. 组合索引

作用:多列可以创建一个索引文件

# 1.创建组合索引
create table user(
    nid int not null auto_increment primary key,   
    name varchar(32) not null,
    email varchar(64) not null,
    extra text      
);

# 将 name 和 email 两列组合成一个索引
create index ix_name_email on user(name,email);

# 组合索引遵循最左前缀,即 where条件必须跟 name 列才会使用索引。

覆盖索引

只需要在索引表中就能获取到数据。

合并索引

# 有两个单独的索引,搜索时使用两个索引
create table user(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name(name) ,
    index ix_email(email)
);

select * from user where name = 'klvchen' or email = 'klvchen@126.com'; 

使用索引注意事项

  • 避免使用select *
  • count(1)或count(列) 代替 count(*)
  • 创建表时尽量时 char 代替 varchar
  • 表的字段顺序固定长度的字段优先
  • 组合索引代替多个单列索引(经常使用多个条件查询时)
  • 尽量使用短索引
  • 使用连接(JOIN)来代替子查询(Sub-Queries)
  • 连表时注意条件类型需一致
  • 索引散列值(重复少)不适合建索引,例:性别不适合
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄