Skip to main content

索引

索引

数据量越大,数据查询的时间越长,查询效率越低,查询一般会进行全表查询。

索引是用来提高数据查询效率的方式,但不是所有的表适合创建索引。

主键索引

以主键字段为索引,创建表时自动创建。

唯一索引

使用唯一字段作为索引,创建表时自动创建。

普通索引

无唯一限制的索引。

组合索引

多字段联合作为索引。

-- 创建唯一索引
create unique index index_field on users(field);

-- 创建普通索引
create index index_field on users(field);

-- 创建组合索引
create index index_field on users(field1,field2)

-- 删除索引
drop index index_field on users;

-- 查询索引
explain select * from users where filed = 'xxx'\G
show create table users\G
show indexes from users;
show keys from users;

优点

  • 减少查询时检索的数据量,提高查询效率。
  • 索引基于 B+ 树算法,已排序,无需再次排序。

缺点

  • 当对数据表进行 DML 时,索引会更新。
  • 索引以文件形式存在,占用硬盘空间。

建议

  • 数据量小,不建议使用索引。
  • 大量 DML 操作时,不建议使用索引。
  • 列数据重复性高的字段,不建议使用索引。