Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ย้ายข้อมูลระหว่างตารางสองตารางที่อยู่ในฐานข้อมูล MySQL ต่างกัน


ใช้คำสั่ง INSERT SELECT รูปแบบ:

INSERT INTO yourDatabaseName1.yourTableName1(yourColumnName1,yourColumnName2,....N)
SELECT yourColumnName1,yourColumnName2,....N FROM yourdatabaseName2.yourTableName2;

ใช้ฐานข้อมูล 2 อันคือ sample และ test

สร้างตารางแรกในฐานข้อมูล test (ตาราง send):

mysql> use test;
Database changed
mysql> create table send
    -> (
    -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> Name varchar(20)
    -> );
Query OK, 0 rows affected (1.19 sec)

เพิ่มข้อมูล:

mysql> insert into send(Name) values('John');
Query OK, 1 row affected (0.20 sec)
mysql> insert into send(Name) values('Carol');
Query OK, 1 row affected (0.40 sec)

แสดงข้อมูล:

mysql> select * from send;
+----+-------+
| Id | Name  |
+----+-------+
| 1  | John  |
| 2  | Carol |
+----+-------+
2 rows in set (0.00 sec)

สร้างตารางที่สองในฐานข้อมูล sample (ตาราง receive) โครงสร้างคอลัมน์ต่างกัน:

mysql> use sample;
Database changed
mysql> create table receive
    -> (
    -> UserId int,
    -> UserName varchar(20)
    -> );
Query OK, 0 rows affected (0.59 sec)

ย้ายข้อมูลจาก test.send ไป sample.receive (แมปคอลัมน์ Id->UserId, Name->UserName):

mysql> insert into sample.receive(UserId,UserName)
    -> select Id,Name from test.send;
Query OK, 2 rows affected (0.21 sec)
Records: 2 Duplicates: 0 Warnings: 0

ตรวจสอบผลลัพธ์:

mysql> select * from receive;
+--------+----------+
| UserId | UserName |
+--------+----------+
| 1      | John     |
| 2      | Carol    |
+--------+----------+
2 rows in set (0.00 sec)