在MySQL中使用带有两个表的UNION的CREATE TABLE AS语句

为此,您可以使用UNION。让我们首先创建一个表-

mysql> create table DemoTable1(FirstName varchar(1000));

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1 values('John');

使用select语句显示表中的所有记录-

mysql> select *from DemoTable1;

这将产生以下输出-

+-----------+
| FirstName |
+-----------+
| John      |
+-----------+
1 row in set (0.02 sec)

这是创建第二个表的查询-

mysql> create table DemoTable2(FirstName varchar(100));

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable2 values('Chris');

使用select语句显示表中的所有记录-

mysql> select *from DemoTable2;

这将产生以下输出-

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

以下是对CREATE TABLE AS语句的查询,并在其中显示两个或多个表的并集-

mysql> create table DemoTable3 AS
   (
      select FirstName, 'DemoTable1' AS `TABLE_NAME` from DemoTable1)
      union
   (
   select FirstName, 'DemoTable2' AS `TABLE_NAME` from DemoTable2);
Records: 2 Duplicates: 0 Warnings: 0

显示表DemoTable3中的所有记录-

mysql> select *from DemoTable3;

这将产生以下输出-

+-----------+--------------+
| FirstName | TABLE_NAME   |
+-----------+--------------+
| John      | DemoTable1   |
| Chris     | DemoTable2   |
+-----------+--------------+
2 rows in set (0.00 sec)