When to generate a temporary table?

We have in the implementation of certain SQL statements may generate a temporary table. We should try to avoid the temporary table, because wasting time and memory temporary table. So under what circumstances would produce a temporary table it?

 

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.[官方说明]

ORDER BY clause and a different GROUP BY clause or ORDER BY clause and a different GROUP BY clause, or ORDER BY or GROUP BY column is not the first table from the JOIN statement sequence, will produce Temporary tables.

Individual test Conclusion:

  1. If no GROUP BY columns in the index, resulting in a temporary table.

  2. If the time GROUP BY, GROUP BY than the SELECT columns a column, and a GROUP BY column is not the primary key, generating a temporary table.

  3. If the GROUP BY columns in the index, ORDER BY column is not indexed. Produce a temporary table.

  4. If the GROUP BY and ORDER BY columns columns are not the same, even if the index will have to generate a temporary table.

  5. If the GROUP BY or ORDER BY column is not a JOIN statement from the first table. Will produce a temporary table.

 

DISTINCT with Combined  ORDER BY On May the require A Temporary Table. [official description]

DISTINCT and ORDER BY may require a temporary table when used with

Individual test Conclusion:

  1. If DISTINCT and ORDER BY columns not indexed, resulting in a temporary table.

 

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.[官方说明]

用了 SQL_SMALL_RESULT, mysql就会用内存临时表。

Individual test Conclusion:

  1. never used this, anyway, it did not generate.

  

 

 

Finally tell you filesort.

The name filesort get too forced a twist. filesort mean just you can not use a sort index to sort, called filesort. He and file did not half dime. filesort should be called sort. This means that if you can not use an existing index to sort, then we need an additional database server for data sorting, this will actually increase the performance overhead.

Published 115 original articles · won praise 101 · views 370 000 +

Guess you like

Origin blog.csdn.net/Alen_xiaoxin/article/details/105269176