sql索引优化实战总结

╰+攻爆jí腚メ 2023-09-28 08:12 132阅读 0赞

sql索引优化实战总结

  • 一、 避免索引失效
    • 1.1 全值匹配
    • 1.2 最左匹配原则
    • 1.3 不再索引列上做任何操作(注意不严谨)
      • 1.3.1 当查询字段为 * 时索引会失效
      • 1.3.1 当查询字段为count(),或者是索引字段 时索引不会失效
    • 1.4 范围条件右边的索引失效
    • 1.5 mysql在使用不等于(!=或者<>)索引失效
    • 1.6 is not null无法使用索引
    • 1.7 like以通配符开头(%qw)索引失效
    • 1.8 字符串不加引号索引失效
    • 1.9 使用or连接索引失效
    • 1.10 尽量使用覆盖索引
  • 二 排序与分组优化
    • 2.1 使用order by出现Using filesort
    • 2.2 使用group by出现Using temporary
  • 三 大数据量分页优化
    • 3.1、数据准备
    • 3.2 测试一下分页数据的相应时间
    • 3.3 子查询优化
    • 使用id限定方案
  • 四 小表驱动大表
    • 4.1 表关联查询
    • 4.2 in和exits查询
  • 五 max函数优化
    • 案例所用sql脚本
    • customer表
    • employee表
    • department表
    • testemployee

一、 避免索引失效

  1. -- 最左匹配原则 *
  2. -- 范围条件右边的索引失效
  3. -- 不再索引列上做任何操作 *
  4. -- 使用不等于(!=或者<>)索引失效
  5. -- is not null无法使用索引
  6. -- like以通配符开头(%qw)索引失效 *
  7. -- 字符串不加引号索引失效
  8. -- 使用or连接索引失效
  9. -- 尽量使用覆盖索引

1.1 全值匹配

  1. -- 创建组合索引
  2. create index idx_name_dep_age on employee(name,dep_id,age)
  3. -- 索引字段全部使用上
  4. explain select * from employee where name='鲁班' and dep_id=1 and age=10

在这里插入图片描述

在这里插入图片描述

1.2 最左匹配原则

  1. -- 去掉name条件 索引全部失效
  2. explain select * from employee where dep_id=1 and age=10

在这里插入图片描述

  1. -- 去掉dep_id name索引生效
  2. explain select * from employee where name='鲁班' and age=10

在这里插入图片描述

  1. -- 顺序错乱不会影响最左匹配
  2. explain select * from employee where dep_id=1 and age=10 and name='鲁班'

在这里插入图片描述

1.3 不再索引列上做任何操作(注意不严谨)

1.3.1 当查询字段为 * 时索引会失效

TRIM(name)=‘鲁班’ 没法通过索引树方式搜索,只能通过遍历索引方式去找

  1. -- name字段上 加上去除空格的函数 索引失效
  2. explain select * from employee where TRIM(name)='鲁班' and dep_id=1 and age=10

在这里插入图片描述

1.3.1 当查询字段为count(),或者是索引字段 时索引不会失效

在这里插入图片描述
在这里插入图片描述
使用到了覆盖索引:
count(*),索引字段这些都不需要回表查询,只要遍历索引树就可以得到了。

1.4 范围条件右边的索引失效

  1. -- 范围查找 会造成该组合索引字段的右侧索引全部失效
  2. explain select * from employee where name = '鲁班' and dep_id>1 and age=10

在这里插入图片描述

1.5 mysql在使用不等于(!=或者<>)索引失效

  1. explain select * from employee where age != 10

在这里插入图片描述

1.6 is not null无法使用索引

  1. explain select * from employee where name is not NULL

在这里插入图片描述

1.7 like以通配符开头(%qw)索引失效

  1. explain select * from employee where name like '%鲁'

在这里插入图片描述
在这里插入图片描述

1.8 字符串不加引号索引失效

  1. explain select * from employee where name = 200

在这里插入图片描述
注意:如果是数字类型加上引号,索引不会失效

  1. explain select * from employee where id = '1'

在这里插入图片描述
隐式类型转换规则:
当字符串类型和数字类型进行比较时候,默认字符串转数字

1.9 使用or连接索引失效

  1. explain select * from employee where name = '鲁班' or age>10

在这里插入图片描述

1.10 尽量使用覆盖索引

  1. explain select * from employee where name = '鲁班' or age>10
  2. -- 覆盖索引: 要查询的字段全部是索引字段
  3. -- 上面情况会触发全表扫描,不过若使用了覆盖索引,则会只扫描索引文件
  4. explain select name,dep_id,age from employee where name = '鲁班' or age>10

二 排序与分组优化

2.1 使用order by出现Using filesort

  1. -- 如果select * 语句未使用到索引,会出现 filesort 可使用覆盖索引解决 主键索引
  2. -- 组合索引不满足最左原则 会出现 filesort
  3. -- 组合索引顺序不一致(order by的后面) 会出现 filesort
  4. -- 当索引出现范围查找时 可能会出现 filesort
  5. -- 排序使用一升一降会造成filesort
  6. -- 没有使用索引排序,服务器需要额外的为数据进行排序的处理
  7. -- 如果select语句未使用到索引,会出现 filesort
  8. explain select * from employee order by name,dep_id,age

在这里插入图片描述

  1. -- 组合索引不满足最左原则 会出现 filesort
  2. explain select * from employee where name='鲁班' order by dep_id,age
  3. explain select * from employee order by dep_id,age

在这里插入图片描述

  1. -- 组合索引顺序不一致(order by的后面) 会出现 filesort
  2. explain select * from employee where name='鲁班' order by dep_id,age
  3. explain select * from employee where name='鲁班' order by age,dep_id

在这里插入图片描述

  1. -- 当索引出现范围查找时 可能会出现 filesort
  2. explain select * from employee where name='鲁班' and dep_id>1 order by age

在这里插入图片描述

  1. -- 排序使用一升一降会造成filesort
  2. explain select * from employee where name='鲁班' order by dep_id desc,age

在这里插入图片描述

2.2 使用group by出现Using temporary

  1. -- order by情况类似, 分组必定触发排序
  2. -- 组合索引不满足最左原则 会出现 filesort
  3. -- 组合索引顺序不一致(order by的后面) 会出现 filesort
  4. -- 当索引出现范围查找时 可能会出现 filesort

三 大数据量分页优化

  1. -- 分页是我们经常使用的功能,在数据量少时单纯的使用limit m,n 不会感觉到性能的影响
  2. -- 但我们的数据达到成百上千万时 就会明显查询速度越来越低

3.1、数据准备

  1. -- 使用存储过程导入数据
  2. -- 查看是否开启函数功能
  3. show variables like 'log_bin_trust_function_creators';
  4. -- 设置开启函数功能
  5. set global log_bin_trust_function_creators=1;
  6. -- 创建函数用于生成随机字符串
  7. delimiter $$
  8. create function rand_string(n int) returns varchar(255)
  9. begin
  10. declare chars_str varchar(100) default 'qwertyuiopasdfghjklzxcvbnm';
  11. declare return_str varchar(255) default '';
  12. declare i int default 0;
  13. while i<n do
  14. set return_str=concat(return_str,substring(chars_str,floor(1+rand()*52),1));
  15. set i=i+1;
  16. end while;
  17. return return_str;
  18. end $$
  19. -- 创建存储过程用于插入数据
  20. delimiter $$
  21. create procedure insert_emp(in start int(10),in max_num int(10))
  22. begin
  23. declare i int default 0;
  24. /*把autocommit设置成0*/
  25. set autocommit= 0;
  26. repeat
  27. set i=i+1;
  28. insert into testemployee(name,dep_id,age,salary,cus_id)
  29. values(rand_string(6),'2',24,3000,6);
  30. until i=max_num end repeat;
  31. commit;
  32. end $$
  33. -- 调用存储过程插入数据
  34. call insert_emp(1,1000000);

3.2 测试一下分页数据的相应时间

  1. -- limit 0,20 时间: 0.001ms
  2. select * from testemployee limit 0,20
  3. -- limit 10000,20 时间: 0.004ms
  4. select * from testemployee limit 10000,20
  5. -- limit 100000,20 时间: 0.044ms
  6. select * from testemployee limit 100000,20
  7. -- limit 1000000,20 时间: 0.370ms
  8. select * from testemployee limit 1000000,20
  9. -- limit 3000000,20 时间: 1.068ms
  10. select * from testemployee limit 3000000,20

3.3 子查询优化

  1. -- 子查询优化
  2. -- 通过Explain发现,之前我们没有利用到索引,这次我们利用索引查询出对应的所有ID
  3. -- 在通过关联查询,查询出对应的全部数据,性能有了明显提升
  4. -- limit 3000000,20 时间: 1.068ms -> 时间: 0.742ms
  5. select * from testemployee e,(select id from testemployee limit 3000000,20) tmp where e.id=tmp.id
  6. -- 自增ID也可以用如下方式
  7. select * from testemployee where id> (select id from testemployee t limit 3000000,1) LIMIT 10

使用id限定方案

  1. -- 使用id限定方案,将上一页的ID传递过来 根据id范围进行分页查询
  2. -- 通过程序的设计,持续保留上一页的ID,并且ID保证自增
  3. -- 时间: 0.010ms
  4. select * from testemployee where id>3000109 limit 20
  5. -- 虽然使用条件有些苛刻 但效率非常高,可以和方案一组合使用 ,跳转某页使用方案一 下一页使用方案2

四 小表驱动大表

4.1 表关联查询

  1. explain select e.id from employee e,department d where e.dep_id=d.id

MySQL 表关联的算法是 Nest Loop Join,是通过驱动表的结果集作为循环基础数据,
然后一条一条地通过该结果集中的数据作为过滤条件到下一个表中查询数据,然后合并结果。
如果小的循环在外层,对于数据库连接来说就只连接5次,进行5000次操作,
如果1000在外,则需要进行1000次数据库连接,从而浪费资源,增加消耗。
这就是为什么要小表驱动大表。

  1. 总结:
  2. 多表查询中,一定要让小表驱动大表
  3. create index idx_dep_id on testemployee(dep_id)
  4. explain select e.id from testemployee e LEFT JOIN department d on e.dep_id=d.id
  5. explain select e.id from testemployee e RIGHT JOIN department d on e.dep_id=d.id

小表驱动大表

4.2 in和exits查询

使用in 时的explain执行计划 d的数据先被查询出来, 根据d的结果集循环查询a表数据

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8iP7lhxZ-1653547861343)(assets/1598535713330.png)]

  1. -- 使用in 时间: 3.292ms
  2. A B
  3. select * from employee where dep_id in (select id from department)
  4. 使用department表中数据作为外层循环 10
  5. for( select id from department d)
  6. 每次循环执行employee表中的查询
  7. for( select * from employee e where e.dep_id=d.id)

使用exits时的explain执行计划 虽然d的查询优先级高,但是当select_type为DEPENDENT_SUBQUERY时,代表当前子查询依赖外部查询,所以可以考到 e表先进行查询

  1. -- 使用exits 时间: 14.771ms
  2. A B
  3. select * from employee e where exists (select 1 from department d where d.id = e.dep_id)
  4. 使用employee表中数据作为外层循环 3000000万次
  5. for(select * from employee e)
  6. 每次循环执行department表中的查询
  7. for( select 1 from department d where d.id = e.dep_id)
  8. 总结:
  9. A表数据多于B表中的数据时,这是我们使用in优于Exists
  10. B表数据多于A表中的数据时,这时我们使用Exists优于in
  11. 如果数据量差不多,那么它们的执行性能差不多
  12. Exists子查询只返回truefalse,因此子查询中的select * 可以是select 1或其它

五 max函数优化

  1. -- max函数中的字段添加索引
  2. select max(age) from testemployee

案例所用sql脚本

customer表

  1. DROP TABLE IF EXISTS `customer`;
  2. CREATE TABLE `customer` (
  3. `id` int(11) NOT NULL,
  4. `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  5. PRIMARY KEY (`id`) USING BTREE
  6. ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  7. -- ----------------------------
  8. -- Records of customer
  9. -- ----------------------------
  10. INSERT INTO `customer` VALUES (1, 'zs');
  11. SET FOREIGN_KEY_CHECKS = 1;

employee表

  1. DROP TABLE IF EXISTS `employee`;
  2. CREATE TABLE `employee` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  5. `dep_id` int(11) NULL DEFAULT NULL,
  6. `age` int(11) NULL DEFAULT NULL,
  7. `salary` decimal(10, 2) NULL DEFAULT NULL,
  8. `cus_id` int(11) NULL DEFAULT NULL,
  9. PRIMARY KEY (`id`) USING BTREE,
  10. INDEX `idx_name_dep_age`(`name`, `dep_id`, `age`) USING BTREE
  11. ) ENGINE = InnoDB AUTO_INCREMENT = 109 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  12. -- ----------------------------
  13. -- Records of employee
  14. -- ----------------------------
  15. INSERT INTO `employee` VALUES (1, '鲁班', 1, 10, 1000.00, 1);
  16. INSERT INTO `employee` VALUES (2, '后裔', 1, 20, 2000.00, 1);
  17. INSERT INTO `employee` VALUES (3, '孙尚香', 1, 20, 2500.00, 1);
  18. INSERT INTO `employee` VALUES (4, '凯', 4, 20, 3000.00, 1);
  19. INSERT INTO `employee` VALUES (5, '典韦', 4, 40, 3500.00, 2);
  20. INSERT INTO `employee` VALUES (6, '貂蝉', 6, 20, 5000.00, 1);
  21. INSERT INTO `employee` VALUES (7, '孙膑', 6, 50, 5000.00, 1);
  22. INSERT INTO `employee` VALUES (8, '蔡文姬', 30, 35, 4000.00, 1);
  23. SET FOREIGN_KEY_CHECKS = 1;

department表

  1. DROP TABLE IF EXISTS `department`;
  2. CREATE TABLE `department` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `deptName` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  5. `address` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  6. PRIMARY KEY (`id`) USING BTREE
  7. ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  8. -- ----------------------------
  9. -- Records of department
  10. -- ----------------------------
  11. INSERT INTO `department` VALUES (1, '研发部(RD)', '2层');
  12. INSERT INTO `department` VALUES (2, '人事部(HR)', '3层');
  13. INSERT INTO `department` VALUES (3, '市场部(MK)', '4层');
  14. INSERT INTO `department` VALUES (4, '后勤部(MIS)', '5层');
  15. INSERT INTO `department` VALUES (5, '财务部(FD)', '6层');
  16. SET FOREIGN_KEY_CHECKS = 1;

testemployee

  1. DROP TABLE IF EXISTS `testemployee`;
  2. CREATE TABLE `testemployee` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  5. `dep_id` int(11) NULL DEFAULT NULL,
  6. `age` int(11) NULL DEFAULT NULL,
  7. `salary` decimal(10, 2) NULL DEFAULT NULL,
  8. `cus_id` int(11) NULL DEFAULT NULL,
  9. PRIMARY KEY (`id`) USING BTREE,
  10. INDEX `idx_age`(`age`) USING BTREE,
  11. INDEX `idx_dep_id`(`dep_id`) USING BTREE
  12. ) ENGINE = InnoDB AUTO_INCREMENT = 2000109 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
  13. -- 使用存储过程导入数据
  14. -- 查看是否开启函数功能
  15. show variables like 'log_bin_trust_function_creators';
  16. -- 设置开启函数功能
  17. set global log_bin_trust_function_creators=1;
  18. -- 创建函数用于生成随机字符串
  19. delimiter $$
  20. create function rand_string(n int) returns varchar(255)
  21. begin
  22. declare chars_str varchar(100) default 'qwertyuiopasdfghjklzxcvbnm';
  23. declare return_str varchar(255) default '';
  24. declare i int default 0;
  25. while i<n do
  26. set return_str=concat(return_str,substring(chars_str,floor(1+rand()*52),1));
  27. set i=i+1;
  28. end while;
  29. return return_str;
  30. end $$
  31. -- 创建存储过程用于插入数据
  32. delimiter $$
  33. create procedure insert_emp(in start int(10),in max_num int(10))
  34. begin
  35. declare i int default 0;
  36. /*把autocommit设置成0*/
  37. set autocommit= 0;
  38. repeat
  39. set i=i+1;
  40. insert into testemployee(name,dep_id,age,salary,cus_id)
  41. values(rand_string(6),'2',24,3000,6);
  42. until i=max_num end repeat;
  43. commit;
  44. end $$
  45. -- 调用存储过程插入数据
  46. call insert_emp(1,1000000);

发表评论

表情:
评论列表 (有 0 条评论,132人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SQL优化(三):SQL优化实战

    前两节基本是讲了SQL优化重要的工具大概思路,你连explain都看不明白,遇到慢查询一个SQL执行半天的情况,估计优化起来肯定无处着手。 这节主要是SQL优化的具体实战,常

    相关 索引优化实战

     一  不要在索引列上做任何计算 不在索引列上做任何操作(计算、函数、(自动 or 手动)类型转换),会导致索引失效而转向全表扫描。 二 实战 等号左边