在 MySQL 中将行从一个表移动到另一个表?
mysqlmysqli database
您可以借助 INSERT INTO SELECT 语句将行从一个表移动到另一个表。
语法如下 −
insert into yourDestinationTableName select *from yourOriginalTable where someCondition
为了理解上述语法。让我们创建一个表。以下是创建表的查询 −
mysql> create table StudentTable −> ( −> Id int, −> Name varchar(100) −> ); Query OK, 0 rows affected (0.65 sec)
现在,我将创建第二个表。查询如下 −
mysql> create table Employee −> ( −> EmployeeId int −> , −> EmployeeName varchar(100) −> ); Query OK, 0 rows affected (0.54 sec)
在 Employee 表中插入一些记录。插入记录的查询如下 −
mysql> insert into Employee values(1,'Carol'); Query OK, 1 row affected (0.18 sec) mysql> insert into Employee values(2,'John'); Query OK, 1 row affected (0.16 sec) mysql> insert into Employee values(3,'Johnson'); Query OK, 1 row affected (0.11 sec)
现在,您可以借助 SELECT 语句显示 Employee 表中的所有记录。查询如下:
mysql> select *from Employee;
以下是输出 −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 1 | Carol | | 2 | John | | 3 | Johnson | +------------+--------------+ 3 rows in set (0.00 sec)
实现我们在开头讨论的语法来移动另一个表中的行。以下查询将行从 Employee 表移动到 StudentTable −
mysql> insert into StudentTable select *from Employee where EmployeeId = 3 and EmployeeName = 'Johnson'; Query OK, 1 row affected (0.17 sec) Records: 1 Duplicates: 0 Warnings: 0
现在,您可以检查该行是否存在于第二个表"StudentTable"中。查询如下 −
mysql> select *from StudentTable;
以下是输出 −
+------+---------+ | Id | Name | +------+---------+ | 3 | Johnson | +------+---------+ 1 row in set (0.00 sec)
查看上面的示例输出,我们将行从一个表移动到另一个表。要移动所有行,只需删除"where"条件。查询如下 −
mysql> insert into StudentTable select *from Employee; Query OK, 3 rows affected (0.15 sec) Records: 3 Duplicates: 0 Warnings: 0
查询显示 StudentTable 中所有更新的记录 −
mysql> select *from StudentTable;
以下是输出 −
+------+---------+ | Id | Name | +------+---------+ | 1 | Carol | | 2 | John | | 3 | Johnson | +------+---------+ 3 rows in set (0.00 sec)