两个表之间的复制值的解决方案,没有类型的所有结构

时间:2012-09-10 04:20:18

标签: php mysql

我使用此代码

update 
contracts a, 
contracts_history b 
set 
a.name_surname=b.name_surname 

我的表有64列,我正在寻找一种解决方案来复制所有数据而不必指定列名 - 沿着以下几行:

 $sql = "INSERT INTO `contracts_history` 
         SELECT * FROM `contracts` WHERE id='$contract_id'";

1 个答案:

答案 0 :(得分:0)

只要您的表与具有匹配数据类型的字段数完全相同,就可以使用insert into select...语法 - 否则您将 使用列名来指定您想要的内容副本。

我刚刚运行以下示例作为示例向您展示语法:

mysql> use test
Database changed
mysql> show tables;
Empty set (0.00 sec)

mysql> create table test1 (id int(2), varry varchar(3));
Query OK, 0 rows affected (0.08 sec)

mysql> create table test2 (id int(2), barry varchar(3));
Query OK, 0 rows affected (0.05 sec)

mysql> insert into test2 values(1,'aaa');
Query OK, 1 row affected (0.00 sec)

mysql> select * from test1;
Empty set (0.00 sec)

mysql> insert into test1 (select * from test2);
Query OK, 1 row affected (0.06 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from test1;
+------+-------+
| id   | varry |
+------+-------+
|    1 | aaa   |
+------+-------+
1 row in set (0.00 sec)

mysql> alter table test2 add column third int(1);
Query OK, 1 row affected (0.06 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> update test2 set barry='ccc';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> insert into test1 (select * from test2);
ERROR 1136 (21S01): Column count doesn't match value count at row 1
mysql>