美文网首页
MySQL数据库索引【index】

MySQL数据库索引【index】

作者: 泡泡龙吐泡泡 | 来源:发表于2018-09-18 21:13 被阅读16次

1. 索引引入

1.1 索引的优点

查询速度块。

1.2 索引的缺点

  1. 增、删、改(数据操作语句)效率降低了。
  2. 做一年占用空间。

2. 索引的类型

  1. 普通索引
  2. 唯一索引(唯一键)
  3. 主键索引:只要设置主键就会自动创建主键索引,不需要手动创建。
  4. 全文索引:搜索引擎使用,MySQL不支持中文的全文索引,我们通过sphinx去解决中文的全文索引。

2.1 创建普通索引【create index】

语法:

create index [索引名] on 表名 (字段名)
alter table 表名 add index [索引的名称] (列名)

例题:

# 创建索引方法一
mysql> create index ix_stuname on stuinfo(stuname);
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

# 创建索引方法二
mysql> alter table stuinfo add index ix_address (stuaddress);
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

# 创建表的时候就添加索引
mysql> create table emp(
    -> id int,
    -> name varchar(10),
    -> index ix_name (name)   # 创建索引
    -> );
Query OK, 0 rows affected (0.00 sec)

2.2 创建唯一索引

语法一:create unique index 索引名 on 表名 (字段名)
语法二:alter table 表名 add unqiue [index] [索引的名称] (列名)
语法三:创建表的时候添加唯一索引,和创建唯一键是一样的。

例题:

# 方法一:
mysql> create unique index UQ_stuname on stu(stuname);
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

# 方法二:
mysql> alter table stu add unique UQ_address (stuaddress);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

# 方法三
mysql> create table stu2(
    -> id int,
    -> name varchar(20),
    -> unique UQ_name(name)
    -> );
Query OK, 0 rows affected (0.01 sec)

2.3 删除索引

语法:

drop index 索引名 on 表名

例题:

mysql> drop index ix_stuname on stuinfo;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

2.4 创建索引的指导原则

  1. 该列用于频繁搜索

  2. 改列用于排序

  3. 公共字段要创建索引

  4. 如果表中的数据很少,不需要创建索引。表中的数据很少时,MySQL搜索索引的时间比逐条搜索数据的时间要长。

  5. 如果一个字段上的数据只有几个不同的值,改字段不适合做索引,比如性别。

相关文章

  • 干货:mysql索引的数据结构

    索引 MySQL官方对索引的定义为:索引(Index)是帮助MySQL高效获取数据的数据结构。 我们知道,数据库查...

  • MySQL索引

    什么是索引 MySQL官方对索引的定义为:索引(Index)是帮助MySQL高效获取数据的数据结构 数据库如何查询...

  • 从原理到优化,深入浅出数据库索引

    MySQL官方对索引的定义为:索引(Index)是帮助MySQL高效获取数据的数据结构。数据库查询是数据库的最主要...

  • elastcisearch5.1.1使用

    ---对应关系 elastcisearch mysql index(索引) 数据库 type(类型) 表 do...

  • 7. Interview-MySQL

    1 MySQL索引类型? 普通索引,index 主键索引,primary 唯一索引,unique index 全文...

  • MySQL数据库索引【index】

    1. 索引引入 1.1 索引的优点 查询速度块。 1.2 索引的缺点 增、删、改(数据操作语句)效率降低了。 做一...

  • 索引(二)

    mysql索引的新手入门详解mysql索引之三:索引使用注意规则 索引(Index)是帮助 MySQL 高效获取数...

  • 9.MySQL索引

    索引(Index)是数据库技术中的一个重要概念与技术,也是MySQL的一个数据库对象。对与任何DBSM,索引都是查...

  • MySQL 索引分类

    MySQL索引的分类(根据数据结构) 索引的本质 MySQL官方对索引的定义为:索引(Index)是帮助MySQL...

  • mysql查询时强制或者禁止使用某个索引

    mysql强制索引和禁止某个索引 1、mysql强制使用索引:force index(索引名或者主键PRI)例如:...

网友评论

      本文标题:MySQL数据库索引【index】

      本文链接:https://www.haomeiwen.com/subject/imzmnftx.html