1. 索引引入
1.1 索引的优点
查询速度块。
1.2 索引的缺点
- 增、删、改(数据操作语句)效率降低了。
- 做一年占用空间。
2. 索引的类型
- 普通索引
- 唯一索引(唯一键)
- 主键索引:只要设置主键就会自动创建主键索引,不需要手动创建。
- 全文索引:搜索引擎使用,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 创建索引的指导原则
-
该列用于频繁搜索
-
改列用于排序
-
公共字段要创建索引
-
如果表中的数据很少,不需要创建索引。表中的数据很少时,MySQL搜索索引的时间比逐条搜索数据的时间要长。
-
如果一个字段上的数据只有几个不同的值,改字段不适合做索引,比如性别。
网友评论