索引index
索引是优化数据库设计,提升数据库性能非常显著的技术之一。
各个字段都可以设计为索引 经常使用的索引为主键索引primary key
索引可以明显提升查询sql语句速度
第一步 alter table emp add primary key (empno);
一旦设置索引,再做数据查询,时间提升是百倍或千倍级的。
什么是索引?
索引本身是一个独立的存储单位,在该单位里边有记录着数据表的某个字段。字段与字段对应的具体的一个物理空间。
索引内部有算法支持,可以使得查询得更快。
序号 名字 身高
104 黄晓明 165
205 奥巴马 185
56 周行知 175
索引空间
字段 ------------------------>物理地址
黄晓明 h 010010012
周行知 z 00x110001293
奥巴马 a 00x11000129
按照索引按照算法排序
奥巴马 a 00x11000129
黄晓明 h 010010012
周行知 z 00x110001293
现实的比喻
例1 站牌-----》公交车 比喻 站牌为索引 公交车 为物理地址
索引类型:
主键:primary key auto_inc
唯一 unique index
普通: index 没有具体要求
全文: fulltext index
索引具体操作
1创建索引
create table student(
id int not null auto_increment comment '主键',
name varchar(32) not null default ' ' comment '名称',
height tinyint not null default 0 comment '身高',
addr varchar(32) not null default ' ' comment '地址',
school varchar(32) not null default ' ' comment '学校',
intro text comment '简介',
//创建索引(主键,唯一,普通,全文)
primary key(id),
//unique index [索引名称] 字段
unique index nm (name),
index(height),
fulltext index(intro)
) engine=myisam charset=utf8;
报错改写成:
create table student(
id int not null auto_increment comment '主键',
name varchar(32) not null default '' comment '名称',
height tinyint not null default 0 comment '身高',
addr varchar(32) not null default '' comment '地址',
school varchar(32) not null default '' comment '学校',
intro text comment '简介',
primary key (id),
unique index nm (name),
index (height),
fulltext index (intro)
)engine=myisam charset=utf8;
输入 show create table student;
创建一个student并且设置一个索引
删除索引
alter table 表名 dropprimary key;//删除主键索引
注意:如果主键存在auto_increment,需要先删除
alter table 表名 modify 主键 int not null comment '主键';
alter table 表名 drop index 索引名称;//删除其他索引(唯一,普通,全文)
alter table student drop primary key;
复合索引:
alter table 表名 add primary key (字段);
其他索引
alter table 表名 add uniqe index 索引名(字段);
alter table 表名 add index 索引名(字段);
alter table 表名 add fulltext index 索引名(字段);
alter table student add index(name ,height);