繁体   English   中英

MySQL:使用来自查询的信息创建新表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM