在 MySQL 中使用 CREATE TABLE AS 语句对两个表进行 UNION 操作

mysqlmysqli database

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

mysql> create table DemoTable1(FirstName varchar(1000));
Query OK, 0 rows affected (1.22 sec)

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

mysql> insert into DemoTable1 values('John');
Query OK, 1 row affected (0.20 sec)

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

mysql> select *from DemoTable1;

这将产生以下输出 −

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

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

mysql> create table DemoTable2(FirstName varchar(100));
Query OK, 0 rows affected (0.81 sec)

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

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

使用 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);
Query OK, 2 rows affected (1.08 sec)
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)

相关文章