您可以借助INSERT INTO SELECT语句将行从一个表移动到另一个表。
语法如下-
insert into yourDestinationTableName select *from yourOriginalTable where someCondition
了解以上语法。让我们创建一个表。以下是创建表的查询-
mysql> create table StudentTable −> ( −> Id int, −> Name varchar(100) −> );
现在,我将创建第二个表。查询如下-
mysql> create table Employee −> ( −> EmployeeId int −> , −> EmployeeName varchar(100) −> );
在表Employee中插入一些记录。插入记录的查询如下-
mysql> insert into Employee values(1,'Carol'); mysql> insert into Employee values(2,'John'); mysql> insert into Employee values(3,'Johnson');
现在,您可以借助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'; 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; 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)