如何移動不同 MySQL 資料庫中列資料的兩張表之間?


為此,您需要使用 INSERT SELECT 語句。語法如下

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

在這裡,我使用以下兩個資料庫

  • 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)

使用 insert 命令在第一張表中插入一些記錄。查詢如下所示

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)

使用 select 語句顯示錶中的所有記錄

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)

如您在上面看到的那樣,我們在第二個表 “receive” 中沒有記錄。

現在,讓我們在不同資料庫中移動包含不同列的 2 個表之間的資料。查詢如下所示

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

顯示錶 sample.receive 中的所有記錄。查詢如下所示。

mysql> select *from receive;

以下是顯示輸出,顯示我們已將日期從一個表成功移至另一個不同資料庫中的表

+--------+----------+
| UserId | UserName |
+--------+----------+
| 1      | John     |
| 2      | Carol    |
+--------+----------+
2 rows in set (0.00 sec)

更新時間:2019 年 7 月 30 日

528 次觀看

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告