首页 > 代码库 > 【MySQL】查询使用临时表

【MySQL】查询使用临时表

MySQL查询产生临时表的分析

官网说明的地址:http://dev.mysql.com/doc/refman/5.5/en/internal-temporary-tables.html

参考:http://blog.csdn.net/chenchaoxing/article/details/25214397

In some cases, the server creates internal temporary tables while processing queries. Such a table can be held in memory and processed by the MEMORY storage engine, or stored on disk and processed by the MyISAM storage engine.
The server may create a temporary table initially as an in-memory table, then convert it to an on-disk table if it becomes too large.
Users have no direct control over when the server creates an internal temporary table or which storage engine the server uses to manage it.在某些情况下,MySQL服务在处理请求时会创建内部临时表,这样被生成的存储在内存中和被处理的临时表是MEMORY存储引擎,异或存储和处理都在磁盘上的临时表为MyISAM存储引擎。MySQL最开始会先创建一个内存中的临时表(后文统一使用“内存临时表”),如果这个表变大MySQL将内存临时表转换成存储在磁盘上临时表(后文统一使用“磁盘临时表”)。用户无法直接控制MySQL何时创建内部临时表,也无法选择内部临时表使用哪种存储引擎。

 

Temporary tables can be created under conditions such as these:1.UNION queries use temporary tables.2.Some views require temporary tables, such those evaluated using the TEMPTABLE algorithm, or that use UNION or aggregation.3.If there is an ORDER BY clause and a different GROUP BY clause, or if the ORDER BY or GROUP BY contains columns from tables other than the first table in the join queue, a temporary table is created.4.DISTINCT combined with ORDER BY may require a temporary table.5.If you use the SQL_SMALL_RESULT option, MySQL uses an in-memory temporary table, unless the query also contains elements (described later) that require on-disk storage.6.Multiple-table UPDATE statements.7.GROUP_CONCAT() or COUNT(DISTINCT) evaluation.以下情况MySQL会创建内部临时表:1、使用UNION的会话。2、一些视图需要临时表,例如评估要使用临时表算法,或UNION和聚合过程。3、ORDER BY子句和GROUP BY子句不同(例如:ORDERY BY price GROUP BY name),或者在JOIN查询中,ORDER BY或者GROUP BY使用了不是第一个表的列(例如:SELECT * from TableA, TableB ORDER BY TableA.price GROUP by TableB.name)。4、DISTINCT与ORDER BY一起使用可能会需要临时表。5、SELECT语句中指定了SQL_SMALL_RESULT关键字 SQL_SMALL_RESULT的意思就是告诉MySQL,结果会很小,请直接使用内存临时表,不需要使用索引排序 SQL_SMALL_RESULT必须和GROUP BY、DISTINCT或DISTINCTROW一起使用 一般情况下,我们没有必要使用这个选项,让MySQL服务器选择即可。6、多个表的更新操作。7、GROUP_CONCAT()和COUNT(DISTINCT)。

 

【MySQL】查询使用临时表