Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join the same table temporary table in MySQL

I like to join a temporary table in MySQL which fails, the idea quite simple:

CREATE TEMPORARY TABLE temp_table LIKE any_other_table; -- srsly it does not matter which table

(
  SELECT p1,p2,p3 FROM temp_table WHERE p4 = 1
) UNION (
  SELECT p1,p2,p3 FROM temp_table WHERE p4 = 2
)

Any help is greatly appreciated.

EDIT: The error thrown by mysql is ERROR 1137 (HY000): Can't reopen table: 'temp_table'

like image 766
Robert Heine Avatar asked Feb 16 '23 06:02

Robert Heine


2 Answers

You cannot refer to a TEMPORARY table more than once in the same query.

Please read the following link http://dev.mysql.com/doc/refman/5.5/en/temporary-table-problems.html

like image 194
vcs Avatar answered Feb 17 '23 21:02

vcs


This should work. Just make sure your new table has a different name then the existing one.

CREATE TEMPORARY TABLE new_table

SELECT p1,p2,p3 FROM existing_table WHERE p4 = 1

UNION 

SELECT p1,p2,p3 FROM existing_table WHERE p4 = 2
;
like image 39
Tom Avatar answered Feb 17 '23 19:02

Tom