在 MySQL 中使用 union 合并两个表?
mysqlmysqli database
要使用 UNION 合并两个表,可以使用 create table select 语句。语法如下 −
create table yourNewTableName select * from yourFirstTableName UNION select * from yourSecondTableName;
首先我们创建一个表。以下是查询 −
mysql> create table FirstTable -> ( -> Id int, -> PersonName varchar(20) -> ); Query OK, 0 rows affected (2.10 sec)
下面是使用 insert 命令在表中插入一些记录的查询 −
mysql> insert into FirstTable values(10,'Larry'); Query OK, 1 row affected (0.12 sec) mysql> insert into FirstTable values(20,'David'); Query OK, 1 row affected (0.22 sec)
以下是使用 select 语句显示表中的所有记录的查询 −
mysql> select * from FirstTable;
这将产生以下输出 −
+------+------------+ | Id | PersonName | +------+------------+ | 10 | Larry | | 20 | David | +------+------------+ 2 rows in set (0.00 sec)
以下是创建第二个表的查询 −
mysql> create table SecondTable -> ( -> Id int, -> PersonName varchar(20) -> ); Query OK, 0 rows affected (0.91 sec)
下面是使用 insert 命令在表中插入一些记录的查询 −
mysql> insert into SecondTable values(30,'Chris'); Query OK, 1 row affected (0.17 sec) mysql> insert into SecondTable values(40,'Robert'); Query OK, 1 row affected (0.15 sec)
现在让我们使用 select 语句显示表中的所有记录 −
mysql> select *from SecondTable;
这将产生以下输出 −
+------+------------+ | Id | PersonName | +------+------------+ | 30 | Chris | | 40 | Robert | +------+------------+ 2 rows in set (0.00 sec)
现在,通过 union 合并两个表(FirstTable + SecondTable)来创建一个表 −
mysql> create table MergeBothTableDemo -> select * from FirstTable -> UNION -> select * from SecondTable; Query OK, 4 rows affected (0.86 sec) Records: 4 Duplicates: 0 Warnings: 0
让我们检查一下新表记录。以下是查询 −
mysql> select * from MergeBothTableDemo;
这将产生以下输出 −
+------+------------+ | Id | PersonName | +------+------------+ | 10 | Larry | | 20 | David | | 30 | Chris | | 40 | Robert | +------+------------+ 4 rows in set (0.00 sec)