如何使用select中的给定列名创建临时表?

时间:2014-05-02 13:16:18

标签: mysql temp-tables create-table

如何使用select?

创建具有给定列名的临时表

我的意思是这样的(我把"作为newData"只是为了说明这个想法,这不起作用):

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

所以我可以得到一个像这样的表:

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

问题是,如果我直接创建表格,第二个字段名称包含禁用符号,我不知道如何使用它:

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

1 个答案:

答案 0 :(得分:2)

as newData正如您所期望的那样工作;

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)