Mysql优化OR条件

x33g5p2x  于2021-03-14 发布在 Mysql  
字(0.5k)|赞(0)|评价(0)|浏览(483)

对于包含OR的查询子句,如果要利用索引,则OR之间的每个条件列都必须用到索引 , 而且不能使用到复合索引; 如果没有索引,则应该考虑增加索引。

获取 emp 表中的所有的索引 :

show index from emp;


示例 :

explain select * from emp where id = 1 or age = 30;

建议使用union 替换or :

我们来比较下重要指标,发现主要差别是 type 和 ref 这两项,type 显示的是访问类型,是较为重要的一个指标,结果值从好到坏依次是:

system > const > eq_ref > ref > fulltext > ref_or_null  > index_merge > unique_subquery > index_subquery > range > index > ALL

UNION 语句的 type 值为 ref,OR 语句的 type 值为 range,可以看到这是一个很明显的差距

UNION 语句的 ref 值为 const,OR 语句的 type 值为 null,const 表示是常量值引用,非常快

这两项的差距就说明了 UNION 要优于 OR

相关文章

微信公众号

最新文章

更多