如何通过将两个表与MySQL Union合并来创建新表?

以下是使用MySQL合并合并两个表的语法

create table yourTableName
(
   select *from yourTableName1
)
UNION
(
   select *from yourTableName2
);

为了理解上述语法,让我们创建一个表。创建第一个表的查询如下

mysql> create table Old_TableDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20)
   -> );

创建第二张表的查询如下

mysql> create table Old_TableDemo2
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20)
   -> );

使用insert命令在第一个表中插入一些记录。查询如下-

mysql> insert into Old_TableDemo(UserName) values('John');
mysql> insert into Old_TableDemo(UserName) values('Carol');

使用select语句显示第一个表中的所有记录。查询如下-

mysql> select *from Old_TableDemo;

以下是输出

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

现在,您可以使用insert命令在第二张表中插入一些记录。查询如下-

mysql> insert into Old_TableDemo2(UserName) values('Larry');
mysql> insert into Old_TableDemo2(UserName) values('Sam');

使用select语句显示第二个表中的所有记录。查询如下-

mysql> select *from Old_TableDemo2;

以下是输出

+--------+----------+
| UserId | UserName |
+--------+----------+
|      1 | Larry    |
|      2 | Sam      |
+--------+----------+
2 rows in set (0.00 sec)

这是通过合并两个具有工会的表来创建新表的查询

mysql> create table UserTableDemo
   -> (
   -> select *from Old_TableDemo
   -> )
   -> UNION
   -> (
   -> select *from Old_TableDemo2
   -> );
Records: 4 Duplicates: 0 Warnings: 0

让我们检查新表的表记录。查询如下-

mysql> select *from UserTableDemo;

以下是输出

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