From c4e3d07a45556156fcff1ebe2f7955a3d450e901 Mon Sep 17 00:00:00 2001 From: guan-songtao <3322619096@qq.com> Date: Sun, 20 Oct 2024 21:15:44 +0800 Subject: [PATCH] test --- .../20241018 \347\264\242\345\274\225.md" | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 "\345\205\263\346\235\276\346\266\233/20241018 \347\264\242\345\274\225.md" diff --git "a/\345\205\263\346\235\276\346\266\233/20241018 \347\264\242\345\274\225.md" "b/\345\205\263\346\235\276\346\266\233/20241018 \347\264\242\345\274\225.md" new file mode 100644 index 0000000..ec20c60 --- /dev/null +++ "b/\345\205\263\346\235\276\346\266\233/20241018 \347\264\242\345\274\225.md" @@ -0,0 +1,99 @@ +# 笔记 + +```sql +-- 普通索引 +create index 索引名 on 表名(字段名);-- 括号里可以有多个字段,运行时遵行左边优先 +-- 查询索引 +show index from 表名; +-- 添加索引(多列) +alter table 表名 add index 索引名(字段名1,字段名2……); +-- 删除索引 +drop index 索引名 on 表名; +-- 在建表时指定索引 +create table 表名( +id int +index 索引名(字段名) +); +-- 建立唯一索引(单列) +create unique index 字段名 on 表名(字段名); +-- 查看有没有用到索引 +explain + 查询语句; +``` + + + +# 练习 + +```sql +- 练习和作业 +-- 1.给emp分别建立 普通索引和唯一索引 +CREATE INDEX idx_name on emp(ename); +CREATE UNIQUE INDEX idx_empno on emp(empno); +-- 2.查询emp表有哪些索引 +show INDEX from emp; +-- 3. 使用有索引的字段进行查询,再查看这条语句是否使用到了索引 +EXPLAIN SELECT * from emp where ename='关羽'; +-- 4. 删除前面建立的两个索引 +drop INDEX idx_name on emp; +alter TABLE emp drop INDEX idx_empno; +-- 5. 选择两个字段添加一个复合索引 +CREATE INDEX idx_sal_comm on emp(sal,comm); +-- 6. 使用复合索引的字段进行查询 +EXPLAIN SELECT * from emp where sal='12500.00' and comm='14000.00'; +``` + +# 作业 + +```sql +-- 作业 +-- 想办法用自己的电脑,生成500万行数据,id,uname,age 尽量随机,并记录时间。 +CREATE TABLE users ( + id INT AUTO_INCREMENT PRIMARY KEY, + uname VARCHAR(255), + age INT +); + +DELIMITER $$ +CREATE PROCEDURE GenerateRandomData() +BEGIN + DECLARE i INT DEFAULT 1; + WHILE i <= 5000000 DO + INSERT INTO users (uname, age) + VALUES ( + CONCAT( + CHAR(FLOOR(RAND() * 26) + 97), + CHAR(FLOOR(RAND() * 26) + 97), + CHAR(FLOOR(RAND() * 26) + 97), + '-', + FLOOR(RAND() * 1000), + FLOOR(RAND() * 1000), + FLOOR(RAND() * 1000) + ), + FLOOR(RAND() * 120) + 1 -- 假设年龄在1到120之间 + ); + SET i = i + 1; + END WHILE; +END$$ +DELIMITER ; + +CALL GenerateRandomData(); +``` + +-- 1. 不用索引查询 一次姓名uname /并记录时间 + +```sql +SELECT * from users where uname='rxp-15950774'; +``` + +![image-20241020210656687](https://gitee.com/guan-songtao/picture-bed/raw/master/image/202410202106819.png) + +-- 2. 建立索引查询 一次姓名uname /并记录时间 + +```sql +CREATE INDEX ind_uname on users(uname); +EXPLAIN SELECT * from users where uname='rxp-15950774'; +``` + +![image-20241020210954293](https://gitee.com/guan-songtao/picture-bed/raw/master/image/202410202109337.png) + +![image-20241020211225239](https://gitee.com/guan-songtao/picture-bed/raw/master/image/202410202112293.png) \ No newline at end of file -- Gitee