MySql(3)

走远了吗. 提交于 2020-02-05 19:29:49

索引

理解索引

前缀索引

索引关键字是表中关键字值的一部分
可以是字段值的组合
不可以跨表创建索引

主索引与聚簇索引

将主关键字作为索引。在MyISAM中,索引关键字的顺序与表中关键字的顺序不必完全相同,称为主索引。在InnoDB中,两者顺序必须完全相同,这种索引称为聚簇索引

索引关键字的选取原则

  1. 离散度高
  2. 存储空间小
  3. 存储空间固定
  4. where子句经常使用
  5. 更新不频繁
  6. 最左前缀原则
e.g.
使用有firstname, lastname, address组成的复合索引(fname_lname_add)就不需要再使用(firstname), (firstname, lastname), (firstname, lastname, address)
  1. 前缀索引

索引与约束

对于一个表而言,主键约束(主索引/聚簇索引),唯一性约束(唯一性索引),外键约束(普通索引)是基于索引实现的

创建索引

Mysql还支持全文索引(fulltext),当检索数据量大的字符串信息时,可以使用全文索引。

  1. 创建表的同时创建索引
create table table_name(
字段1 数据类型 [约束条件].
字段2 数据类型 [约束条件].
……
[其他约束条件],
[其他约束条件],
[unique|fulltext] index [索引名] (字段名 [(长度)] [asc | desc])
) engine =  xxx default charset = xxx;
# []中为可选项,()为必选项
# 长度为索引中关键字的字符长度,关键字的值时数据库表中的一部分,即前缀索引
e.g.
create table book(
isbn char(10) primary key,
name char(100) not null,
brief_introduction text not null,
price decimal(6,2),
publish_time  date not null,
unique index isbn_unique (isbn),
index name_index (name (20)),
fulltext index brief_fulltext (name, brief_introduction),
index complex_index (price, publish_time)
) engine = MyISAM charset = gbk;
  1. 在已有表上创建索引
语法1.
create [unique|fulltext] index 索引名 on 表名 (字段名 [(长度)] [asc|desc]);
语法2.
alter table 表名 add [unique|fulltext] index 索引名 (字段名 [(长度)] [asc|desc]);
e.g.
alter table course add fulltext index description_fulltext (descrpition);
等价于
create fulltext table index description_fulltext on course (description);

删除索引

drop index index_name on table_name;
e.g.
drop index complex_index on book;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!