如何通过将两个表与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)
热门推荐
10 薛之谦祝福语简短
11 七一祝福语明信片文案简短
12 收到公公生日祝福语简短
13 孩子满月随礼简短祝福语
14 步入高中祝福语简短励志
15 公司年终晚会祝福语简短
16 家人毕业祝福语简短励志
17 春节拜年祝福语儿童简短
18 横幅元旦祝福语大全简短