mysql8.0 之 sql 优化《二》 之 select 优化 where 字句优化 总览总结

版权声明:本文为博主原创文章,转载注明出处,欢迎多多交流,乐在沟通,有需要请联系邮箱:[email protected] https://blog.csdn.net/weixin_42749765/article/details/88227280

介绍:

文章中介绍的 select ... where  字句 中的优化 适用于 delete or update

重点

为了提高where 子句 的性能 可能会牺牲一点 代码可读性 ,因为mysql 会自动执行类似的优化,所以要避免 where 字句的写法。

删除不必要的括号:

((a and b ) and c or (((a and b) and ( c and d))))

改为:(a and b and c) or(a and b and c and d)

恒定折叠:

(a<b and b=c) and a = 5

改为: b>5 and b=c and a=5

恒定条件取出:

(b>=5 and b=5) or (b=6 and 5=5) or (b=7 and 5=6)

改为:b=5 or b=6

在MySQL 8.0.14及更高版本中一些策略

  • 索引使用的额表达式只计算一次
  • count(*)在没有a的表单上 where 直接从表信息 MyISAM 和 MEMORY 表中检索获得。
  • not null 只一个表查询的时候用,也可以在表达式中使用。
  • 早期检测无效常量表达式,是不反回任何行的。
  • havingwhere 如果不适用 group by 或聚合函数count(),min()等,则合并 
  • 对于链接中的每个表,where 构造一个简单的where 表来快速检索表,并尽快跳过行

 

查询中任何其他表之前首先读取所有常量表。下边介绍常量表

  • 一张空表或一行表。
  • 与a或 index where 上的字句一起使用的表,其中所有索引部分都与常量表达式进行比较定义为:primary  keyuniquenot null
select * from t where primary_key=1;

select *from t1,t2 where t1.primary_key=1 and t2.primary_key=t1.id
  • 最佳链接组合,如果 order by 和 group by 句子中的列都来自同一个表,那么再加入是首先该选这个表。
  • 如果order by 字句和不同的group by 字句,或order by 或者 group by 包含链接队列中第一个表以外的列,则会创建临时表。
  • 如果使用了 sql_small_result 修饰符,mysql 会使用内存零时表。
  • 大部分情况使用最佳索引,除非优化程序使用表扫描更有效,根据最佳索引是否跨域超过表的30%使用扫描,但百分比不一定决定使用索引和扫描的最大因素,优化器还会(根据表大小,行数i/o快大小) 进行估算选择。
  • 一些情况下,mysql 不用咨询数据文件直接从索引中读取行。如果索引中使用的都是数字则可以使用索引树来解析查询。
  • 没输出一行之前,having将跳过与该字句不匹配的行。

 

一些查询非常快的示例:

select count(*) from tab;

select min(key_par1) ,max(key_par1) from tab;

select max(key_part2) from tab where key_part1 = constant;

select ... from tab order by key_part1,key_part2,.....limit 10;

select ... from tab order by key_part1 desc, key_part2 desc, .... limit 10;

 

mysql 仅使用索引树解析查询,假设索引的列都是数字:

select key_p1,key_p2 from tab where key_p1 = val;

select count(*) form tab where key_p1 =val1 and key_par2 = val2;

select key_p2 from tab group by key_p1;

使用索引来排序检索,而不是单独的排序传递:

select ... from tab order by key_p1,keyp2...;

select ... from tab order by key_p1 desc , keyp_2 desc , ....;

上一篇 总结 mysql 优化 内容:https://blog.csdn.net/weixin_42749765/article/details/88223273

文章持续更新,转发表明出处方便更新!

猜你喜欢

转载自blog.csdn.net/weixin_42749765/article/details/88227280