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

mysqlmysqli database更新于 2024/1/9 14:41:00

为此,请使用 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)

相关文章