如何在 MySQL 中合併兩張表並新增一個新列,其中包含記錄?


我們首先建立一個表 −

mysql> create table DemoTable1
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.76 sec)

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

mysql> insert into DemoTable1(Name) values('Chris');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable1(Name) values('Robert');
Query OK, 1 row affected (0.13 sec)

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

mysql> select *from DemoTable1;

輸出

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

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

mysql> create table DemoTable2
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.48 sec)

使用插入命令在第二個表中插入一些記錄 −

mysql> insert into DemoTable2(Name) values('David');
Query OK, 1 row affected (0.53 sec)

mysql> insert into DemoTable2(Name) values('Bob');
Query OK, 1 row affected (0.15 sec)

使用 select 語句顯示第二個表中的所有記錄 −

mysql> select *from DemoTable2;

輸出

+----+-------+
| Id | Name  |
+----+-------+
|  1 | David |
|  2 | Bob   |
+----+-------+
2 rows in set (0.00 sec)

以下是向兩個表並集新增新列的查詢 −

mysql> select Id,Name, 27 AS Age from DemoTable1
   -> union
   -> select Id,name,20 AS Age from DemoTable2;

輸出

+----+--------+-----+
| Id | Name   | Age |
+----+--------+-----+
|  1 | Chris  | 27  |
|  2 | Robert |  27 |
|  1 | David  | 20  |
|  2 | Bob    | 20  |
+----+--------+-----+
4 rows in set (0.00 sec)

更新日期:30-Jul-2019

466 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.