Bạn có thể di chuyển hàng giữa các bảng với câu lệnh INSERT INTO SELECT.
Cú pháp:
insert into yourDestinationTableName select *from yourOriginalTable where someCondition
Tạo bảng để minh họa:
mysql> create table StudentTable -> ( -> Id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.65 sec)
Tạo bảng thứ hai:
mysql> create table Employee -> ( -> EmployeeId int, -> EmployeeName varchar(100) -> ); Query OK, 0 rows affected (0.54 sec)
Chèn dữ liệu vào 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)
Hiển thị Employee:
mysql> select *from Employee;
Kết quả:
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 1 | Carol | | 2 | John | | 3 | Johnson | +------------+--------------+ 3 rows in set (0.00 sec)
Di chuyển hàng từ Employee sang 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
Kiểm tra StudentTable:
mysql> select *from StudentTable;
Kết quả:
+------+---------+ | Id | Name | +------+---------+ | 3 | Johnson | +------+---------+ 1 row in set (0.00 sec)
Để di chuyển tất cả hàng, bỏ điều kiện where:
mysql> insert into StudentTable select *from Employee; Query OK, 3 rows affected (0.15 sec) Records: 3 Duplicates: 0 Warnings: 0
Kiểm tra lại:
mysql> select *from StudentTable;
Kết quả:
+------+---------+ | Id | Name | +------+---------+ | 1 | Carol | | 2 | John | | 3 | Johnson | +------+---------+ 3 rows in set (0.00 sec)