V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
silenceeeee
V2EX  ›  问与答

MySQL 临时表的问题

  •  
  •   silenceeeee · 2016-11-27 18:08:37 +08:00 · 1094 次点击
    这是一个创建于 2722 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如下表结构:

    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.
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2778 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 03:06 · PVG 11:06 · LAX 20:06 · JFK 23:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.