MySQL——索引

索引
一、索引介绍
1、什么是索引?
(1)定义:索引是一种数据结构
索引是表中的已一种约束表格数据的一种结构;
(2)索引是在表的字段上创建的
如:id 、name、sex 对字段约束
(3)索引包含了一列值,这个值保存在一个数据结构中
2、索引作用?
(1)保证数据记录的唯一性
(2)实现表与表之间的参照性
(3)减少排序和分组的时间(例如在使用order by ,group by 查询语句中进行数据检索)
(4)可以使用索引快速访问数据库中指定信息
3、索引的缺点?
(1)索引要占物理内存
(2)索引对表进行增删改查,索引要动态维护,降低数据的维护速度

二、索引的分类
1、主键索引 (primary key)简写:pri
一个表中只能有一个,不能为空,唯一
添加主键
格式:
ALTER table 表名 add PRIMARY key (字段名)
如:
ALTER table s2 add PRIMARY key (id)
2、唯一索引 (unique) 简写uni
格式:
alter table 表名 add UNIQUE 索引名(字段名)
如:alter table s2 add UNIQUE sym(name)

一个表中可以有多个,能为空,唯一
3、普通索引 简写mull
最基本的索引,没有任何限制
格式:alter table 表名 add INDEX 索引名(字段名)
如:alter table s3 add INDEX sym(id)
image

三、索引的使用
1、查询索引
(1)格式:show index from 表名 ;
show index from s2 ;
image
e02b5e04c3b938842cce7fa5d959780e

(2)格式:show keys from 表名;
show keys from s2;
image
2abf3e78d991c936fe2ee40f398a0048

2、desc 查看索引简写,索引
image
7e2ca7fc9fcb561c1947ebd8c1430f41

3、删除普通索引和唯一索引
格式;
ALTER table 表名 drop index 索引名 ;
如:
ALTER table s2 drop index sym ;
image

4、删除主键索引
格式:
ALTER table 表名 drop PRIMARY key ;

ALTER table s2 drop PRIMARY key ;
image

四、约束
1、默认值:default
2、不为空 not null
3、 自增长:auto_incremnet 一般和主键一期使用
4、主键:primary key
5、唯一:unique
建表:
create table x1(id int(10) PRIMARY key auto_increment,name varchar(20) UNIQUE ,
sex int(10) not null ,age int(10) DEFAULT 18)DEFAULT CHARSET=utf8
select * from x1 ;
desc x1
image
7753d2a998ee8139068f037f4ff79395

四、
1、什么是索引?
2、索引的作用?
3、如何创建索引?
4、主键索引和唯一索引的区别?

posted @ 2026-01-23 15:03  软件测试小董  阅读(3)  评论(0)    收藏  举报