什么是索引

按照平常的理解,如果我们需要查找数据,就得通过遍历数据表的方式一个个查找,直到查找到匹配的数据为止;在数据量比较少的情况下可以这样操作,但是当使用 mysql 存储的数据量很大时,如果我们也一个个遍历的话那么查找速度就会很慢。这时,我们就需要用到索引,使用索引可以大大提高 mysql 的检索速度。

创建索引时,你需要确保该索引是作为 SQL 查询语句的条件(一般作为 where 子句的条件)。

实际上,索引也是一张表,该表保存了主键与索引字段,并指向实体表的记录。简单的说,索引就是通过某种方式能够快速地查找到对应的东西。

但是索引也不能滥用,使用索引可以提高查询速度,但同时也会降低更新表的速度,更新表时,(insert\update\delete)Mysql不仅要保存数据,还要保存索引,建立索引会占用磁盘空间的索引文件。

索引的分类

  • 单列索引:一个索引只包含单个列,一个表可以有多个单列索引
  • 组合索引:一个索引包含多个列

mysql操作索引

显示索引信息

  1. // show index from 表名;
  2. > show index from student;

普通索引

最基本的索引,它没有任何限制。创建方式如下:

创建索引

  1. -- create index index_name on 表名(字段名);
  2. create index index_name on student(name(32));

创建表的时候直接指定

create table student(
    id int not null,
    username varchar(16) not null,
    index [indexName] (字段名)
);

删除索引的语法

-- drop index [indexName] on 表名;
drop index index_name on student;

唯一索引

索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。创建方式如下:

# create unique index indexName on 表名(字段名([length]))
create unique index index_name on student(name);

例如:

-- 唯一索引,创建之后不能再创建相同名字的值,否则报错;
create unique index index_name on student(name);

select * from student;

+----+-----------+-----+---------------+--------+
| id | name      | age | register_date | gender |
+----+-----------+-----+---------------+--------+
|  1 | 小明      |  23 | 2019-07-12    | 男     |
|  2 | 张三      |  20 | 2019-07-02    | 男     |
|  4 | 张小娴    |  40 | 2019-08-05    | 女     |
| 11 | 李四      |  20 | 2010-04-06    | 男     |
+----+-----------+-----+---------------+--------+

-- 再次创建一条名字叫小明的数据
insert into student(name,age,register_date,gender) values("小明",25,"2018-06-01","男");
-- error: Duplicate entry '小明' for key 'index_name'