讓我輕輕的告訴你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/ 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM