要连接两个表,MySQL中的UNION ALL。让我们创建一个表-
mysql> create table DemoTable1 ( Id int, FirstName varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1 values(10,'John'); mysql> insert into DemoTable1 values(20,'Carol');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable1;
输出结果
+------+-----------+ | Id | FirstName | +------+-----------+ | 10 | John | | 20 | Carol | +------+-----------+ 2 rows in set (0.00 sec)
创建第二个表。
mysql> create table DemoTable2 ( Id int, FirstName varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2 values(20,'David'); mysql> insert into DemoTable2 values(40,'Chris');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable2;
输出结果
+------+-----------+ | Id | FirstName | +------+-----------+ | 20 | David | | 40 | Chris | +------+-----------+ 2 rows in set (0.00 sec)
以下是连接两个表的查询-
mysql> select *from DemoTable1 where Id=20 union all select *from DemoTable2 where Id=20;
输出结果
+------+-----------+ | Id | FirstName | +------+-----------+ | 20 | Carol | | 20 | David | +------+-----------+ 2 rows in set (0.43 sec)