diff --git "a/\345\220\264\344\275\263\345\256\207/20241018 \347\264\242\345\274\225\347\273\203\344\271\240\344\270\216\344\275\234\344\270\232.md" "b/\345\220\264\344\275\263\345\256\207/20241018 \347\264\242\345\274\225\347\273\203\344\271\240\344\270\216\344\275\234\344\270\232.md" new file mode 100644 index 0000000000000000000000000000000000000000..db8e0e0ceaff745203909744f516267f87b1aaba --- /dev/null +++ "b/\345\220\264\344\275\263\345\256\207/20241018 \347\264\242\345\274\225\347\273\203\344\271\240\344\270\216\344\275\234\344\270\232.md" @@ -0,0 +1,86 @@ +#### 索引: + +1. ##### 概念 + + 索引是数据库表中一个特殊的数据结构,用于快速查找和访问表中的数据。它类似于书籍的目录。加速数据检索,优化查询性能,避免全表扫描。 + +2. ##### 类型 + + - 单列索引:只包含单个列的索引。 + - 复合索引:由多个列组成的索引,用于加速涉及多个列的查询,使用要遵循最左原则。 + - 唯一索引:确保索引列中的值是唯一的,不允许重复。 + - 主键索引:一种特殊的唯一索引,且不允许为空,通常用于唯一标识一行数据。 + - 全文索引:用于对文本数据进行全文检索,主要用于查找大文本字段中的关键词。 + - 空间索引:用于地理数据类型的索引,加速空间查询。 + +3. ##### 语法: + + ```sql + -- 创建索引 + create index 索引名 on 表名(字段名); + alter table 表名 add index 索引名(字段名); + + -- 建表时 + create table 表名( + id int primary key auto_increment, + 字段名 类型, + index 索引名 (字段名) + ); + + -- 删除索引 + drop index 索引名 on 表名; + alter table 表名 drop index 索引名; + + -- 查看查询的执行计划,分析索引的使用情况 + explain select * from 表名 WHERE 条件; + ``` + +```sql +-- 练习和作业 +-- 1.给emp分别建立 普通索引和唯一索引 +create index two on emp(job); +create unique index one on emp(ename); + +-- 2.查询emp表有哪些索引 +show index from emp; +-- 3. 使用有索引的字段进行查询,再查看这条语句是否使用到了索引。 +select * from emp where ename = '刘备'; +EXPLAIN select * from emp where ename = '刘备'; +-- 4. 删除前面建立的两个索引 +drop index one on emp; +alter table emp drop index two; +-- 5. 选择两个字段添加一个复合索引 +create index three on emp(ename,job); +-- 6. 使用复合索引的字段进行查询 +select * from emp where ename = '刘备' and job = '经理'; -- 0.294s + +-- 作业 +-- 想办法用自己的电脑,生成500万行数据,id,uname,age 尽量随机,并记录时间。 +-- 1. 不用索引查询 一次姓名uname /并记录时间 +select * from tuser where user_name = '姓名_77777'; -- 4.15s + +-- 2. 建立索引查询 一次姓名uname /并记录时间 +create index tname on tuser(user_name); +select * from tuser where user_name = '姓名_77777'; -- 0.302s + +create table tuser( +id int(11) not null auto_Increment, +user_name varchar(255) default null, +primary key(id) +); + +create procedure a() +begin +declare number int; +set number = 1;1 +while number <= 5000000 DO +insert into tuser(user_name) +values (concat('姓名_',number)); +set number = number + 1; +end while; +end; +call a(); +``` + +![Snipaste_2024-10-19_20-03-43](https://gitee.com/WJY-7/first-base/raw/master/images/202410192004361.png) +