2011-07-06 38 views
21

在MySQL中,我想創建一個新的表,在該查詢的所有信息:MySQL的:從查詢創建與信息的新表

select * into consultaa2 from SELECT 
CONCAT( 'UPDATE customers SET 
customers_default_address_id= ',  
(SELECT a.address_book_id FROM 
address_book a where 
c.customers_id=a.customers_id order by 
address_book_id desc limit 1), ' 
WHERE customers_id = ', customers_id, 
';') AS sql_statement FROM customers c 
where c.customers_id > 3894; 

查詢太長瀏覽器中顯示concat和我需要這個來做這個更新。

回答

14

插入到具有與查詢信息的表格式

INSERT INTO <TABLE-1> 
SELECT * FROM <TABLE-2> 

在你的情況下,這將是

insert into consultaa2 
SELECT CONCAT('UPDATE customers SET customers_default_address_id= ', 
(SELECT a.address_book_id FROM address_book a where c.customers_id=a.customers_id order by address_book_id desc limit 1), ' WHERE customers_id = ', customers_id, ';') AS sql_statement FROM customers c where c.customers_id > 3894; 

只要確保在要插入到表中的列並從select查詢返回的列匹配。

+0

你知道我試過相同,沒有工作,我只是意識到,因爲它是一個查詢MySQL的不知道要創建什麼類型的字段,真的很瘋狂,但通過手動創建表和字段來修復:) – Saikios

+1

@ daniel-hilgarth答案實際上是Saikios問題的正確答案,因爲它會基於選定的表結構創建新表。 Saikios查詢語法看起來很像TSQL語法。 –

86

你可以這樣說:

CREATE TABLE tablename SELECT * FROM othertable; 

tablename是你要創建的新表的名稱,SELECT * FROM othertable是返回表應該從創建的數據查詢。

+0

是否可以這樣做,但只能創建一個臨時表? – kevando

+1

@kevando是的,它是:'CREATE TEMPORARY TABLE tablename AS(SELECT * FROM othertable);' – pymkin

+0

是否可以像這樣做,但添加一個額外的字段不在原始查詢?例如,我想爲表添加一個主鍵,如'id INT NOT NULL AUTO_INCREMENT PRIMARY KEY'。如何才能做到這一點? – Metafaniel

7

MySQL的創建新表從MySQL命令行

實施例。

mysql> create table foo(id int, vorta text); 
Query OK, 0 rows affected (0.02 sec) 

插入行

mysql> insert into foo values(1, 'for the hoarde'); 
Query OK, 1 row affected (0.00 sec) 

看看裏面有什麼了

mysql> select * from foo; 
+------+----------------+ 
| id | vorta   | 
+------+----------------+ 
| 1 | for the horde | 
+------+----------------+ 
1 row in set (0.00 sec) 

從查詢創建信息的新表

mysql> create table foo2 select * from foo; 
Query OK, 1 row affected (0.01 sec) 
Records: 1 Duplicates: 0 Warnings: 0 

檢查數據移動

mysql> select * from foo2; 
+------+----------------+ 
| id | vorta   | 
+------+----------------+ 
| 1 | for the horde | 
+------+----------------+ 
1 row in set (0.00 sec)