使用 UNION ALL 在 MYSQL 中使用單一查詢在兩張表中插入記錄


以下是建立第一張表的查詢。

mysql> create table DemoTable1
   -> (
   -> StudentName varchar(20),
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.67 sec)

為了理解以上概念,我們建立一個第二張表。

mysql> create table DemoTable2
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.61 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable2 values('Chris');
Query OK, 1 row affected (0.12 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select * from DemoTable2;

將生成以下輸出 -

+-------+
| Name  |
+-------+
| Chris |
+-------+
1 row in set (0.00 sec)

以下是使用單一 MySQL 查詢選擇和插入記錄的查詢 -

mysql> insert into DemoTable1
   -> select Name,89 from DemoTable2
   -> union all
   -> select Name,98 from DemoTable2;
Query OK, 2 rows affected (0.15 sec)
Records: 2  Duplicates: 0  Warnings: 0

現在你可以從第一張表中選擇記錄 -

mysql> select * from DemoTable1;

將生成以下輸出 -

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           89 |
| Chris       |           98 |
+-------------+--------------+
2 rows in set (0.00 sec)

更新日期:10-Dec-2019

878 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.