糯米文學吧

位置:首頁 > IT認證 > Linux認證

Linux數據庫MySQL內部臨時表策略

MySQL內部臨時表的使用有一定的策略,從源碼中關於SQL查詢是否需要內部臨時表。可以總結如下:

Linux數據庫MySQL內部臨時表策略

1、DISTINCT查詢,但是簡單的INCT查詢,比如對primary key、unique key等DISTINCT查詢時,查詢優化器會將DISTINCT條件優化,去除DISTINCT條件,也不會創建臨時表;

2、不是第一個表的字段使用ORDER BY 或者GROUP BY;

3、ORDER BY和GROUP BY使用不同的順序;

4、用户需要緩存結果;

5、ROLLUP查詢。

源碼如下所示

代碼地址:sql_, 函數:JOIN::optimize(),位置:sql_

/*

Check if we need to create a temporary table.

This has to be done if all tables are not already read (const tables)

and one of the following conditions holds:

- We are using DISTINCT (simple distincts are already optimized away)

- We are using an ORDER BY or GROUP BY on fields not in the first table

- We are using different ORDER BY and GROUP BY orders

- The user wants us to buffer the result.

When the WITH ROLLUP modifier is present, we cannot skip temporary table

creation for the DISTINCT clause just because there are only const tables.

*/

need_tmp= (( const_tables != tables &&

(( select_distinct || !simple_order || !simple_group) ||

( group_list && order ) ||

test(select_options & OPTION_BUFFER_RESULT))) ||

( e != ROLLUP:: STATE_NONE && select_distinct ));

內部臨時表使用原則

但是使用了內部臨時表,那麼他是怎麼存儲的呢?原則是這樣的:

1、當查詢結果較小的情況下,使用heap存儲引擎進行存儲。也就是説在內存中存儲查詢結果。

2、當查詢結果較大的情況下,使用myisam存儲引擎進行存儲。

3、當查詢結果最初較小,但是不斷增大的情況下,將會有從heap存儲引擎轉化為myisam存儲引擎存儲查詢結果。

什麼情況算是查詢結果較小呢?從源碼中if的幾個參數可以看出:

1、有blob字段的情況;

2、使用唯一限制的情況;

3、當前表定義為大表的情況;

4、查詢結果的選項為小結果集的情況;

5、查詢結果的選項為強制使用myisam的情況。