让我轻轻的告诉你AliSQLselect语句中in多少个合适

在以往的分享中,不止一次被开发问:

blob.png

MySQL的官方手册上有这么一句话:

the optimizer can estimate the row count for each range using dives into the index or index statistics.

这是在说: 优化器为每一个范围段(如“a IN (10, 20, 30)”是等值比较, 括3个范围段实则简化为3个单值,分别是10,20,30)估计每个范围段(用范围段来表示是因为MySQL的“range”扫描方式多数做的是范围扫描,此处单值可视为范围段的特例)中包括的元组数, 而估计方法有2种,一是dive到index中即利用索引完成元组数的估算,简称index dive; 二是使用索引的统计数值,进行估算:

相比这2种方式,在效果上:

1 index dive: 速度慢,但能得到精确的值(MySQL的实现是数索引对应的索引项个数,所以精确)

2 index statistics: 速度快,但得到的值未必精确

     简单说,选项 eq_range_index_dive_limit 的值设定了 IN列表中的条件个数上线,超过设定值时,会将执行计划从 1 变成 2。

为什么要区分这2种方式呢?

简单地说:

1 查询优化器使用代价估算模型计算每个计划的代价,选择其中代价最小的

2 单表扫描时,需要计算代价;所以单表的索引扫描也需要计算代价

3 单表的计算公式通常是:代价=元组数*IO平均值

4 所以不管是哪种扫描方式,都需要计算元组数

5 当遇到“a IN (10, 20, 30)”这样的表达式的时候,发现a列存在索引,则需要看这个索引可以扫描到的元组数由多少而计算其索引扫描代价,所以就用到了本文提到的“index dive”、“index statistics”这2种方式。

MySQL据此,提供了一个参数“eq_range_index_dive_limit”,指示MySQL在这种情况下使用哪种方式。用法如下:

This variable indicates the number of equality ranges in an equality comparison condition when the optimizer should switch from using index dives to index statistics in estimating the number of qualifying rows. It applies to evaluation of expressions that have either of these equivalent forms, where the optimizer uses a nonunique index to look up col_name values:

col_name IN(val1, ..., valN)

col_name = val1 OR ... OR col_name = valN

默认设置是10,一直到5.7以后的版本默认会修改成200,当然我们是可以手动设置的。我们看下5.6手册中的说明:

The eq_range_index_dive_limit system variable enables you to configure the number of values at which the optimizer switches from one row estimation strategy to the other. To disable use of statistics and always use index dives, set eq_range_index_dive_limit to 0. To permit use of index dives for comparisons of up to N equality ranges, set eq_range_index_dive_limit to N + 1.
eq_range_index_dive_limit is available as of MySQL 5.6.5. Before 5.6.5, the optimizer uses index dives, which is equivalent to eq_range_index_dive_limit=0.

也就是说:

1. eq_range_index_dive_limit = 0 只能使用index dive
2. 0 < eq_range_index_dive_limit <= N 使用index statistics
3. eq_range_index_dive_limit > N 只能使用index dive

AliSQL的配置:

blob.png

参考资料:

http://myrock.github.io/2014/09/24/in-and-range/ 

http://blog.163.com/li_hx/blog/static/18399141320147521735442/ 

原文地址:https://www.cnblogs.com/sunss/p/6118816.html