官方文档:
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)。