從 MySQL 中的多張表插入記錄


要從多張表插入記錄,請使用 INSERT INTO SELECT 語句。在此處,我們將從 2 張表中插入記錄。

我們先建立一個表 −

mysql> create table DemoTable1943
   (
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令向表中插入一些記錄 −

mysql> insert into DemoTable1943 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1943 values('Robert');
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from DemoTable1943;

這將生成以下輸出 −

+--------+
| Name   |
+--------+
| Chris  |
| Robert |
+--------+
2 rows in set (0.00 sec)

以下是建立第二個表的查詢 −

mysql> create table DemoTable1944
   (
   Age int
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令向表中插入一些記錄 −

mysql> insert into DemoTable1944 values(23);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1944 values(26);
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from DemoTable1944;

這將生成以下輸出 −

+------+
| Age  |
+------+
|   23 |
|   26 |
+------+
2 rows in set (0.00 sec)

以下是建立第三個表的查詢 −

mysql> create table DemoTable1945
   (
   StudentName varchar(20),
   StudentAge int
   );
Query OK, 0 rows affected (0.00 sec)

以下是從多張表插入資料的查詢 −

mysql> insert into DemoTable1945(StudentName,StudentAge) select tbl1.Name,tbl2.Age from DemoTable1943 tbl1,DemoTable1944 tbl2;
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

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

mysql> select * from DemoTable1945;

這將生成以下輸出 −

+-------------+------------+
| StudentName | StudentAge |
+-------------+------------+
| Chris       |         23 |
| Robert      |         23 |
| Chris       |         26 |
| Robert      |         26 |
+-------------+------------+
4 rows in set (0.00 sec)

更新時間:2019 年 12 月 31 日

5K+ 瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.