MySQL 临时表的问题

2016-11-27 18:08:37 +08:00
 silenceeeee

如下表结构:

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `column1` varchar(10) DEFAULT NULL,
  `column2` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

用 EXPLAIN 查看:

EXPLAIN SELECT  * FROM test ORDER BY column1

显示不会创建临时表

EXPLAIN SELECT  * FROM test GROUP BY column1

显示会创建临时表

为什么?

以下是官方关于什么情况下会创建临时表的说明:

In some cases, the server creates internal temporary tables while processing statements. Users have no direct control over when this occurs.

The server creates temporary tables under conditions such as these:

Evaluation of UNION statements, with some exceptions described later.

Evaluation of some views, such those that use the TEMPTABLE algorithm, UNION, or aggregation.

Evaluation of derived tables (subqueries in the FROM clause).

Tables created for subquery or semi-join materialization (see Section 9.2.1.18, “ Subquery Optimization ”).

Evaluation of statements that contain an ORDER BY clause and a different GROUP BY clause, or for which the ORDER BY or GROUP BY contains columns from tables other than the first table in the join queue.

Evaluation of DISTINCT combined with ORDER BY may require a temporary table.

For queries that 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.

Evaluation of multiple-table UPDATE statements.

Evaluation of GROUP_CONCAT() or COUNT(DISTINCT) expressions.
1095 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/323646

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX