From cbdc37540d391c57ee2d4a0f64500072525bc1b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=94=A1=E5=98=89=E4=B9=90?= <3196825236@qq.com> Date: Thu, 19 Oct 2023 05:20:19 +0000 Subject: [PATCH] =?UTF-8?q?13=20=E8=94=A1=E5=98=89=E4=B9=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 蔡嘉乐 <3196825236@qq.com> --- .../\347\264\242\345\274\225.md" | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 "13 \350\224\241\345\230\211\344\271\220/\347\264\242\345\274\225.md" diff --git "a/13 \350\224\241\345\230\211\344\271\220/\347\264\242\345\274\225.md" "b/13 \350\224\241\345\230\211\344\271\220/\347\264\242\345\274\225.md" new file mode 100644 index 0000000..6db4bf2 --- /dev/null +++ "b/13 \350\224\241\345\230\211\344\271\220/\347\264\242\345\274\225.md" @@ -0,0 +1,76 @@ +```mysql +## 索引 + +### 笔记 + +**索引**是帮助MySQL高效获取数据的数据结构 + +不使用索引会直接查询整个表,表越大,时间越长 + +##### 创建索引三种方式 + +1. 在已存在表的中创建索引 + +~~~mysql +create index 索引名 on 表名(字段名) +~~~ + +2. 通过修改表方式赖添加索引 + +~~~mysql +alter table 表名 add index 索引名(字段名) +~~~ + +3. 创建表时直接指定索引 + +建立索引时一定要指定索引名称 + +##### 其他语法 + +- 查看索引 + +~~~mysql +show index from 表名 +~~~ + +- 删除索引 + +~~~mysql +drop index 索引名 on 表名 +~~~ + +##### 索引类别 + +1. 唯一索引 + 1. 建立列的唯一约束时,会自动产生唯一索引,这样子的话列名就是索引名 +2. 主键索引 + 1. 建立列的主键约束时,会自动产生唯一索引,这样子的话列名就是索引名 + 2. 特殊唯一索引,不允许有空值 +3. 普通索引 + +##### 最左前缀法则 + +从左开始,左边的索引必须要存在,从左往右查 + +#### 运行时间 + +![image-20231019073559282](https://s2.loli.net/2023/10/19/X2jkBphmY6Vn1LD.png) + +#### 作业 + +~~~mysql +-- 执行查询文件tb_user.sql,数据准备好了之后,完成如下需求: +-- 1. name字段为姓名字段,该字段的值可能会重复,为该字段创建索引。 +create index idx_name on tb_user(name); +-- 2. phone手机号字段的值,是非空,且唯一的,为该字段创建唯一索引。 +create unique index idx_phone on tb_user(phone); +-- 3. 为profession、age、status创建联合索引。 +create index idx_pas on tb_user(profession,age,`status`); +drop index idx_pas on tb_user; +-- 4. 为email建立合适的索引来提升查询效率。 +create unique index idx_email on tb_user(email); +-- 5. 查看tb_user表的所有的索引数据。 +show index from tb_user; +~~~ +``` + -- Gitee