MySQL内部临时表对策

MySQL内部临时表策略

     通过对MySQL数据库源码的跟踪和调试,以及参考MySQL官方文档,对MySQL内部临时表使用策略进行整理,以便于更加深入的理解。

使用内部临时表条件

     MySQL内部临时表的使用有一定的策略,从源码中关于SQL查询是否需要内部临时表。可以总结如下:

     1、DISTINCT查询,但是简单的DISTINCT查询,比如对primary key、unique key等DISTINCT查询时,查询优化器会将DISTINCT条件优化,去除DISTINCT条件,也不会创建临时表;

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

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

     4、用户需要缓存结果;

     5、ROLLUP查询。


     源码如下所示

     代码地址:sql_select.cc:854,函数:JOIN::optimize(),位置:sql_select.cc:1399


  
/*

    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 distinct’s 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

免责声明: 本文仅代表作者个人观点,与无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。

相关资料

MySQL内部临时表对策

相关文章:

你感兴趣的文章:

标签云: