mysql中MyISAM引擎下三种索引的使用

索引的介绍

索引相当于目录结构,其内部有一定的算法,可以快速的帮我们定位到,相应的数据位置.

索引的示意图:MyISAM


图片.png

1 每一条数据记录都有其相应的位置,且有一个内部的编号.
2 为某一个字段建立了索引之后,会保存关键字和记录的位置,而且索引是按一定的顺序排序的.
3 如果我们要找yang这个记录,先根据索引文件找到对应的位置,再根据位置找到数据库对应的记录,而不需要将保存数据的文件进行整个扫描
4 现在查找一个xiao的记录,因为索引文件中后的数据都是经过排序的,那么当找到li和yang直间没有这个记录,就不再向下寻找.

使用索引与不用的区别

a 新建有主键的表myisam_1和没有主键的表myisam_2

create table myisam_1(
id mediumint auto_increment primary key,
name varchar(10) not null 
)engine=myisam;

insert into myisam_1 values(1,'段誉');
insert into myisam_1 values(11,'虚竹');
insert into myisam_1 values(5,'乔峰');
insert into myisam_1 values(6,'王语嫣');
insert into myisam_1 values(9,'天山童老');
insert into myisam_1 values(8,'慕容复');
   
insert into myisam_1 select null,name from myisam_1;
create table myisam_2(
id mediumint,
name varchar(10) not null 
)engine=myisam;
insert into myisam_2 values(1,'段誉');
insert into myisam_2 values(11,'虚竹');
insert into myisam_2 values(5,'乔峰');
insert into myisam_2 values(6,'王语嫣');
insert into myisam_2 values(9,'天山童老');
insert into myisam_2 values(8,'慕容复');

// 执行数据的插入,多执行几次,插入1w+数据
insert into myisam_2 select * from myisam_1

b 对比两个表的查询速度,查询where id=5的数据


图片.png

查询myisam_1


图片.png

四种索引形式

primary key 主键索引保证数据的唯一性,而且不能为空
unique 唯一索引 防止数据出现重复
index(key) 普通索引 仅仅只是为了提高查询的速度
fulltext 全文索引(不支持中文)
复合索引:就是多个字段同时建立索引,如 alter table emp add index(field1,field2)
所有的索引都可以实现提高查询的速度的功能.

建表的时候创建索引

在建表的时候直接添加主键索引,唯一索引,普通索引,全文索引等.

id mediumint not null auto_increment,
sn char(10) not null default 0 comment '学号',
xing varchar(10) not null default '' comment '姓',
ming varchar(10) not null default '' comment '名',
info text,
primary key(id),
unique(sn),
index(xing,ming),
fulltext(info)
)engine=MyISAM default charset=utf8;
图片.png

查看创建成功的表的结构
show create table study \G

图片.png

使用desc查看表的结构


图片.png

修改表的结构增加索引

除了主键索引,其他索引设置的同时可以给其起一个”名称”,名称不设置与该索引字段名称一致
给存在的数据表增加索引

alter table 表名 add  unique key [索引名称]  (字段);
alter table 表名 add  key  [索引名称]  (字段);
alter table 表名 add  fulltext key  [索引名称]  (字段);

这里的索引名称都是可以不写的,那么默认就是字段的名称.

a 先添加一张表

create table study1(
id mediumint not null,
sn char(10) not null default 0 comment '学号',
xing varchar(10) not null default '' comment '姓',
ming varchar(10) not null default '' comment '名'
)engine=myisam default charset='utf8';

b 为已经创建好的表增加索引

alter table study1 add primary key(id);   // 主键索引
alter table study1 add unique sn(sn);     // 给学号增加唯一索引
alter table study1 add index x_m(xing,ming);  // 给xingming添加复合索引
图片.png

c 查看已经建立好的索引:


图片.png

总结:

1 主键索引(primary key)是全表唯一的,字段类型一般是数字,只能有一个,一般和自增长(auto_increment)结合起来使用.可以限制字段的唯一.
2 唯一索引(unique或index),表中可以有多个,主要是限制字段不能出现重复.
3 全文索引(fulltext),只支持英文,不支持中文.中文的分词要使用sphinx,后续的文章会说.
4 所有的索引,都会增加查询的速度,数据超快10W+,会体现出来.
5 索引也不是越多越好,新建索引后在MYISAM中会新增文件,文件体积大时,也降低查询的效率.

你可能感兴趣的:(mysql中MyISAM引擎下三种索引的使用)