mysql索引,mysql创建索引,mysql删除索引
1.在关系数据库中,索引是一种与表有关的数据库结构,它可以使对应于表的sql语句执行得更快。今天就简单地给大家演示一下mysql中索引的创建,查询以及删除。
2.首先随便建立一张表,sql语句如下:
create table if not exists `student` (
`id` int(11) not null auto_increment comment '学号',
`name` varchar(64) not null default '' comment '姓名',
`sex` tinyint(1) not null comment '性别',
`age` tinyint(2) not null comment '年龄',
`class` varchar(64) not null default '' comment '班级',
primary key (`id`)
) engine=myisam default charset=utf8 comment='学生表';
3.可以看到,在创建表的sql语句中,已经建立了一个主键索引,此时查看表中索引:show index from `student`,结果如图所示:
4.当然,我们还可以在基础上添加别的索引,比如说唯一索引。假设每个学生的名字是不可以重复的,那么就可以在name字段上添加一个唯一索引:
alter table `student` add unique `stu_name` (`name`);
此时,再次查看表中索引,show index from `student`,结果如图所示:
5.然后再给班级添加一个普通索引:
alter table `student` add index `stu_class` (`class`);
查看表中索引,show index from `student`,结果如图所示:
6.接下来是删除索引,删除掉唯一索引和普通索引:
alter table `student` drop index `stu_name`;
alter table `student` drop index `stu_class`;
然后查看表中索引,show index from `student`,结果如图所示:
7.这时,就剩下一个主键索引了,如果直接删除的话将会报错:
alter table `student` drop primary key;
原因:因为主键索引关联的id键为自动增长;
8.需要先将id键的自动增长取消:
alter table `student` modify `id` int(10) not null comment '学号'
再次执行:
alter table `student` drop primary key;
查看表中索引,show index from `student`,表中已经没有索引啦
以上就是mysql如何创建和删除索引?的详细内容。