Question

How to create temporary table with given column names from select?

I mean something like this (I put "as newData" just to illustrate the idea, this doesn't work):

 CREATE TEMPORARY TABLE IF NOT EXISTS tmp AS
 SELECT id, min(data) as newData FROM myTable WHERE id > 100 GROUP BY id;

So I can get a table like:

+-------------------+------------------+------+-----+---------+-------+
| Field             | Type             | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------+-------+
| id                | int(10) unsigned | NO   |     | 0       |       |
| newData           | int(10) unsigned | YES  |     | NULL    |       |
+-------------------+------------------+------+-----+---------+-------+

The problem is that if I create the table directly, the second field name contains forbidden symbols and I don't know how to use it:

+-------------------+------------------+------+-----+---------+-------+
| Field             | Type             | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------+-------+
| id                | int(10) unsigned | NO   |     | 0       |       |
| min(data)         | int(10) unsigned | YES  |     | NULL    |       |
+-------------------+------------------+------+-----+---------+-------+
Était-ce utile?

La solution

as newData works just as you'd expect it to;

mysql> CREATE TABLE myTable (
  id INT NOT NULL DEFAULT 0,
  data INT
);

mysql> CREATE TEMPORARY TABLE tmp AS
         SELECT id, min(data) as newData FROM myTable WHERE id > 100 GROUP BY id;

mysql> desc tmp;
+---------+---------+------+-----+---------+-------+
| Field   | Type    | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| id      | int(11) | NO   |     | 0       |       |
| newData | int(11) | YES  |     | NULL    |       |
+---------+---------+------+-----+---------+-------+
2 rows in set (0.01 sec)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top