# 创建普通索引
alter table 表名 add index 索引名(字段);
alter table stu add index idx_name(name);
# 查看索引
show index from 表名;
desc 表名;
# 索引类型
PRI:主键索引
UNI:唯一键索引
MUL:普通索引
# 删除索引
alter table 表名 drop index 索引名;
alter table stu drop index idx_name;
# 添加主键索引
altre table 表名 add primary key(字段);
alter table stu add primary key(name);
# 删除主键索引
alter table 表名 drop primary key;
# 添加唯一键索引
alter table 表名 add unique key 索引名(字段);
alter table stu add unique key uni_name(name);
## 添加唯一键要求:该字段的数据不能有重复名# 删除唯一键索引
alter table 表名 drop index 索引名
alter table stu drop index uni_name;
# 判断是否可以在该字段上创建唯一键
1.先统计该字段总共有多少行
select count(name) from stu;
2.再统计,去重后,该字段有多少行
select count(distinct(name)) from stu;
3.查看两个数据的结果是不是一样的,如果是一样的则可以创建唯一键索引,如果两个数值不一样,则无法创建唯一键索引
前缀索引(给某一字段数据内容特别长的列,创建前缀索引)
# 普通前缀索引的创建
alter table 表名 add index 索引名(字段(数字))
alter table stu add index idx_name(name(3));
# 唯一键索引前缀索引创建
alter table 表名 add unique key 索引名(字段(数字))
注:
1.避免对大列(数据长的列)建索引
2.如果要建,那么用前缀索引
联合索引(将多个字段,做成一个索引)
# 联合索引的查询顺序要和创建是的顺序一致,才可以提高效率# 普通联合索引创建
alter table 表名 add index 索引名(字段1,字段2...)
alter table stu add index idx_all(id,name);
# 主键联合索引创建
alter table 表名 add primary key (字段1,字段2...)
alter table stu add primary key (id,name);
# 唯一键联合查询
alter table 表名 add unique key 索引名(字段1,字段2...)
alter table stu add unique key unq_all(id,name);
## 索引无法直接修改,删除索引后重新创建
index:全索引扫描,将创建索引的列的全部数剧都查询出来
例:
explain select id from stu;
range:范围查询,一般来说,一条SQL语句,只要达到该级别即可
例:
explain select * from stu whereid>2;
ref:唯一键索引的前缀扫描或者非唯一索引扫描(精确查询)
例
explain select * from stu whereid=1;
eq_ref:连表查询,传统连接,join on
例:
explain select stu.name,stude.id from stu join stude on stu.id=stude.id and stu.id='4';
const、system:主键精确查询
例:
explain select * from stu where name='jd';
null:不进行表的扫描,一个不存在的条件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端