MySQL数据库之索引

索引

  • 概述
    • 优点
      • 加快查询速度
    • 缺点
      • 带索引的表在数据库中需要更多的存储空间
      • 增、删、改命令需要更长的处理时间,因为它们需要对索引进行更新

创建索引的指导原则

  • 适合创建索引的列

    • 该列用于频繁搜索
    • 该列用于对数据进行排序
    • 在WHERE子句中出现的列,在join子句中出现的列
  • 请不要使用下面的列创建索引

    • 列中仅包含几个不同的值
    • 表中仅包含几行。为小型表创建索引可能不太划算,因为MySQL在索引中搜索数据所花的时间比在表中逐行搜索所花的时间更长

创建索引

  • 主键索引

    • 主要创建了主键就会自动的创建主键索引
  • 唯一索引

    • 创建唯一键就创建了唯一索引

唯一索引与普通索引

  • 说明

    • 创建主键就会创建主键索引
    • 创建唯一键就会创建唯一索引
    • 索引创建后,数据库根据查询语句自动选择索引
  • 创建唯一键的语法

    • create unique [index] 索引名 on 表名(字段名)
    • alter table 表名 add uniqe [index] 索引名(字段名)
  • 创建普通索引的语法

    • create index 索引名 on 表名(字段名)
    • alter table 表名 add index 索引名(字段名)

唯一索引的创建

  • 创建表的时候添加唯一索引
create table t5(
    id int primary key,
    name varchar(20),
    unique ix_name(name)
);
  • 给表添加唯一索引
mysql> create table t5(
    -> name varchar(20),
    -> addr varchar(50)
    -> );
# `Query OK, 0 rows affected (0.00 sec)`

mysql> create unique index ix_name on t5(name);
# `Query OK, 0 rows affected (0.06 sec)`
# `Records: 0  Duplicates: 0  Warnings: 0`
  • 通过更改表的方式创建唯一索引
mysql> alter table t5 add unique ix_addr (addr);
# `Query OK, 0 rows affected (0.00 sec)`
# `Records: 0  Duplicates: 0  Warnings: 0`

普通索引的创建

  • 创建表的时候添加普通索引
mysql> create table t6(
    -> id int primary key,
    -> name varchar(20),
    -> index ix_name(name)
    -> );
# `Query OK, 0 rows affected (0.02 sec)`
  • 给表添加普通索引
mysql> create table t7(
    -> name varchar(20),
    -> addr varchar(50)
    -> );
# `Query OK, 0 rows affected (0.00 sec)`

mysql> create index ix_name on t7(name) ;
# `Query OK, 0 rows affected (0.08 sec)`
# `Records: 0  Duplicates: 0  Warnings: 0`
  • 通过更改表的方式创建索引
mysql> alter table t7 add index ix_addr(addr);
# `Query OK, 0 rows affected (0.02 sec)`
# `Records: 0  Duplicates: 0  Warnings: 0`

删除索引

  • 语法
    • drop index 索引名 on 表名
mysql> drop index ix_name on t7;
# `Query OK, 0 rows affected (0.01 sec)`
# `Records: 0  Duplicates: 0  Warnings: 0`
posted @ 2020-12-15 13:19  wing1377  阅读(82)  评论(0编辑  收藏  举报