如何在 MySQL 中从一个表向另一个表复制行?


为此,请使用 INSERT INTO SELECT 语句。让我们首先创建一个表 -

mysql> create table DemoTable1879
   (
   Id int,
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable1879 values(101,'Chris Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1879 values(102,'David Miller');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1879 values(103,'Adam Smith');
Query OK, 1 row affected (0.00 sec)

使用 select 语句显示表中的所有记录 -

mysql> select * from DemoTable1879;

这将产生以下输出 -

+------+--------------+
| Id   | Name         |
+------+--------------+
|  101 | Chris Brown  |
|  102 | David Miller |
|  103 | Adam Smith   |
+------+--------------+
3 rows in set (0.00 sec)

以下是创建第二个表的查询 -

mysql> create table DemoTable1880
   (
   ClientId int,
   ClientName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

以下是将行从一个表复制到另一张表中的查询 -

mysql> insert into DemoTable1880(ClientId,ClientName) select Id,Name from DemoTable1879 where Id IN(101,103);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

使用 select 语句显示表中的所有记录 -

mysql> select * from DemoTable1880;

这将产生以下输出 -

+----------+-------------+
| ClientId | ClientName  |
+----------+-------------+
|      101 | Chris Brown |
|      103 | Adam Smith  |
+----------+-------------+
2 rows in set (0.00 sec)

更新于: 2019-12-27

3K+ 浏览量

开启您的职业生涯

完成课程,获得认证

入门
广告