索引
理解索引
前缀索引
索引关键字是表中关键字值的一部分
可以是字段值的组合
不可以跨表创建索引
主索引与聚簇索引
将主关键字作为索引。在MyISAM
中,索引关键字的顺序与表中关键字的顺序不必完全相同,称为主索引。在InnoDB
中,两者顺序必须完全相同,这种索引称为聚簇索引
索引关键字的选取原则
- 离散度高
- 存储空间小
- 存储空间固定
where
子句经常使用- 更新不频繁
- 最左前缀原则
e.g.
使用有firstname, lastname, address组成的复合索引(fname_lname_add)就不需要再使用(firstname), (firstname, lastname), (firstname, lastname, address)
- 前缀索引
索引与约束
对于一个表而言,主键约束(主索引/聚簇索引),唯一性约束(唯一性索引),外键约束(普通索引)是基于索引实现的
创建索引
Mysql还支持全文索引(fulltext),当检索数据量大的字符串信息时,可以使用全文索引。
- 创建表的同时创建索引
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.
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;
来源:CSDN
作者:人总是要有梦想的QAQ
链接:https://blog.csdn.net/qq_43410618/article/details/104184993