如何在 MySQL 中合并两张表并添加一个新列,其中包含记录?
我们首先创建一个表 −
mysql> create table DemoTable1 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.76 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable1(Name) values('Chris'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1(Name) values('Robert'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable1;
输出
+----+--------+ | Id | Name | +----+--------+ | 1 | Chris | | 2 | Robert | +----+--------+ 2 rows in set (0.00 sec)
以下是创建第二个表的查询 −
mysql> create table DemoTable2 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.48 sec)
使用插入命令在第二个表中插入一些记录 −
mysql> insert into DemoTable2(Name) values('David'); Query OK, 1 row affected (0.53 sec) mysql> insert into DemoTable2(Name) values('Bob'); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示第二个表中的所有记录 −
mysql> select *from DemoTable2;
输出
+----+-------+ | Id | Name | +----+-------+ | 1 | David | | 2 | Bob | +----+-------+ 2 rows in set (0.00 sec)
以下是向两个表并集添加新列的查询 −
mysql> select Id,Name, 27 AS Age from DemoTable1 -> union -> select Id,name,20 AS Age from DemoTable2;
输出
+----+--------+-----+ | Id | Name | Age | +----+--------+-----+ | 1 | Chris | 27 | | 2 | Robert | 27 | | 1 | David | 20 | | 2 | Bob | 20 | +----+--------+-----+ 4 rows in set (0.00 sec)
广告