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

时间:2011-07-06 10:55:22

标签: mysql sql insert sql-update

在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,我需要这个来进行更新。

3 个答案:

答案 0 :(得分:116)

你可以这样做:

CREATE TABLE tablename SELECT * FROM othertable;

tablename是您要创建的新表的名称,SELECT * FROM othertable是返回应从中创建表的数据的查询。

答案 1 :(得分:20)

使用查询信息插入表格的格式为

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查询返回的列匹配。

答案 2 :(得分:9)

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)
相关问题