1.重点:索引是一种数据结构
2.索引的作用 可以利用索引快速访问数据库中的特定信息.
3.索引分类
3.1 普通索引
3.2 唯一索引
3.3 主键索引
create table bb (id int(10) primary key,name varchar(10),class int(10));
desc bb;
insert into bb values (1,'xiaoduan',1833),(2,'xiaoduan',1835);
select * from bb;
1、创建普通索引==》这是最基本的索引,它没有任何限制
create index tt on bb(id); ==》给id字段创建一个名为tt的普通索引
show index from bb; ==》查看bb表添加的索引
create index a on bb(name,class); ==》给 字段name 和class 添加普通索引a
alter table bb drop index tt; ==》把索引tt删除
2、唯一索引 ==》与普通索引不同的是索引的值必须唯一,但是可以为空
create unique index t on bb(name); ==>[Err] 1062 - Duplicate entry 'xiaoduan' for key 't' 报错,值有重复
create unique index t on bb(id);
show index from bb; ==》查看bb表添加的索引
alter table bb drop index t; ==》把索引t删除
3、主键索引 ==》不可为空 也不能重复和主键约束相辅相成 (创表时加了主键其实已经创建了主键索引)
alter table bb drop primary key; ==》 删除主键约束,同时也是删除主键索引
desc bb;
alter table bb add primary key (id); ==》创建主键索引
show index from bb; ==》查看bb表创建了哪些索引
alter table bb change id id int(10) primary key; ==》给id字段添加主键约束,同时添加了主键索引
面试题:主键和唯一索引的区别?
1、主键是一种约束,唯一索引是索引,本质不一样
2、主键创建后包含一个唯一索引,但是唯一索引不一定包含主键
3、主键不能为空和重复,唯一索引可以为空
4、一个表只能有一个主键,但是可以有多个唯一索引
5、主键适合唯一标识,如身份证
总结:
优点:
1、可以保证数据的唯一性
2、加快查询
3、提高性能
缺点:
维护耗时间
占物理空间
|
|