Crear una tabla temporal en una instrucción SELECT sin una TABLA CREATE separada


¿Es posible crear una tabla temporal (solo sesión) a partir de una instrucción select sin utilizar una instrucción create table y especificar cada tipo de columna? Sé que las tablas derivadas son capaces de esto, pero son super-temporales (solo declaración) y quiero reutilizar.

Ahorraría tiempo si no tuviera que escribir un comando create table y mantener la lista de columnas y la lista de tipos emparejados.

Author: einpoklum, 2011-05-02

5 answers

CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1)

Del manual encontrado en http://dev.mysql.com/doc/refman/5.7/en/create-table.html

Puede usar la palabra clave TEMPORAL al crear una tabla. Una tabla TEMPORAL es , visible sólo para la sesión actual, y quitan automáticamente cuando se cierra la sesión. Esto significa que dos sesiones diferentes pueden usar el mismo nombre de tabla temporal sin entrar en conflicto entre sí o con una tabla no TEMPORAL existente del mismo nombre. (El la tabla existente se oculta hasta que se elimina la tabla temporal.) Para crear tablas temporales, debe tener el privilegio CREAR TABLAS TEMPORALES.

 709
Author: psparrow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 10:30:37

Además de la respuesta de psparrow si necesita agregar un índice a su tabla temporal, haga lo siguiente:

CREATE TEMPORARY TABLE IF NOT EXISTS 
  temp_table ( INDEX(col_2) ) 
ENGINE=MyISAM 
AS (
  SELECT col_1, coll_2, coll_3
  FROM mytable
)

También funciona con PRIMARY KEY

 121
Author: RafaSashi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-13 11:09:56

Utilice esta sintaxis:

CREATE TEMPORARY TABLE t1 (select * from t2);
 56
Author: rizon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-21 07:10:53

El motor debe estar antes de seleccionar:

CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY 
as (select * from table1)
 53
Author: Crusader,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-14 14:02:25

ENGINE=MEMORY no se admite cuando la tabla contiene BLOB/TEXT columnas

 33
Author: Cris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-21 07:11:55