Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate Temporary Table MySQL

Tags:

mysql

I want to reference a temporary table multiple times in the same query. Due to the problem with temporary tables I cannot do that:

http://dev.mysql.com/doc/refman/5.7/en/temporary-table-problems.html

So to fix that I'm creating duplicates of the temporary table:

CREATE TEMPORARY TABLE IF NOT EXISTS earnings_temp_one AS (SELECT * FROM earnings WHERE earning_account_id = ?);
CREATE TEMPORARY TABLE IF NOT EXISTS earnings_temp_two AS (SELECT * FROM earnings WHERE earning_account_id = ?);
CREATE TEMPORARY TABLE IF NOT EXISTS earnings_temp_three AS (SELECT * FROM earnings WHERE earning_account_id = ?);

But this requires me to query the massive table earnings 3 times, which to some extent defeats the purpose.

Is there a way for me to duplicate a temporary table, under a different name?

Then I could run the query on the massive table just once.

Or maybe there's a fix to the temporary table problem that doesn't require me to create duplicates?

like image 680
Amy Neville Avatar asked Jan 21 '16 11:01

Amy Neville


People also ask

What is MySQL temporary table?

In MySQL, a temporary table is a special type of table that allows you to store a temporary result set, which you can reuse several times in a single session. A temporary table is very handy when it is impossible or expensive to query data that requires a single SELECT statement with the JOIN clauses.

How long does MySQL temporary table last?

What are Temporary Tables? Temporary tables were added in the MySQL Version 3.23. If you use an older version of MySQL than 3.23, you cannot use the temporary tables, but you can use Heap Tables. As stated earlier, temporary tables will only last as long as the session is alive.

Where are MySQL temp tables stored?

An internal temporary table can be held in memory and processed by the MEMORY storage engine, or stored on disk by the InnoDB or MyISAM storage engine. If an internal temporary table is created as an in-memory table but becomes too large, MySQL automatically converts it to an on-disk table.

How do I SELECT a temporary table in MySQL?

The general syntax would be like this: INSERT INTO temporary_tabel_name SELECT * FROM existing table_name; Following the general syntax, we will copy the data from the existing table, named, Guys into the newly created temporary table, named, “temporary_data”.


1 Answers

Ok, I solved it:

CREATE TEMPORARY TABLE IF NOT EXISTS earnings_temp_one AS (SELECT * FROM earnings WHERE earning_account_id = ?);
CREATE TEMPORARY TABLE IF NOT EXISTS earnings_temp_two AS (SELECT * FROM earnings_temp_one);
CREATE TEMPORARY TABLE IF NOT EXISTS earnings_temp_three AS (SELECT * FROM earnings_temp_one);
like image 88
Amy Neville Avatar answered Nov 02 '22 23:11

Amy Neville