一.ICP
注意一下ICP的使用條件:
只能用於二級索引(secondary index)。
explain顯示的執行計劃中type值(join 類型)爲range、 ref、 eq_ref或者ref_or_null。且查詢需要訪問表的整行數據,即不能直接通過二級索引的元組數據獲得查詢結果(索引覆蓋)。
ICP可以用於MyISAM和InnnoDB存儲引擎,不支持分區表(5.7將會解決這個問題)。
二.order by .. limit ...優化
from mysql 5.6.2 開始對order by .. limit ...優化:
select col1,col2 from tx order by no_key_col limit offset,rowcount;
From 5.6.2 by treating the sort buffer as a priority queue:
Scan the table, inserting the select list columns from each selected row in sorted order in the queue. If the queue is full, bump out the last row in the sort order.
Return the first
N
rows from the queue. (IfM
was specified, skip the firstM
rows and return the nextN
rows.)
Before 5.6.2,Previously, the server performed this operation by using a merge file for the sort:
Scan the table, repeating these steps through the end of the table:
Select rows until the sort buffer is filled.
Write the first
N
rows in the buffer (M
+N
rows ifM
was specified) to a merge file.
Sort the merge file and return the first
N
rows. (IfM
was specified, skip the firstM
rows and return the nextN
rows.)
The cost of the table scan is the same for the queue and merge-file methods, so the optimizer chooses between methods based on other costs:
The queue method involves more CPU for inserting rows into the queue in order
The merge-file method has I/O costs to write and read the file and CPU cost to sort it
算法:
5.6使用queue:
把select 的列放入隊列裏,當隊列滿了把隊列最後的出隊列,就是把最大的、次大的、.....依次推到隊列的前面,表所有行的列全部放完後,把第一個前rowcount 出隊列,依次進行,都在sort buffer 裏排序。
5.6之前:使用 merge file
把row insert 到 sort buffer,sort buffer相當於一個堆棧,sort buffer被插滿了,依次把當前堆棧裏前面的rowcount出隊列放入到merge file,直到所有的排好序,然後通過merge file 再排序取出結果。
後續 ...........................