[英]MySQL: Creating a new table with information from a query
在 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,我需要它來進行更新。
你可以這樣做:
CREATE TABLE tablename SELECT * FROM othertable;
tablename
是您要創建的新表的名稱, SELECT * FROM othertable
是返回應創建表的數據的查詢。
*請注意,此方法不會創建表(根據 OP 標題)。 為此,請參閱此答案。 *
使用來自查詢的信息插入到表中的格式為
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 查詢返回的列匹配即可。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.