2014-05-02 84 views
1

如何使用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 |  | 
+-------------------+------------------+------+-----+---------+-------+ 

回答

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) 
+0

哦,真的)我測試了它錯誤。謝謝。 – klm123