使用UNION从两个表中选择。让我们首先创建一个表-
mysql> create table DemoTable1 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1(FirstName) values('Chris') ; mysql> insert into DemoTable1(FirstName) values('Adam'); mysql> insert into DemoTable1(FirstName) values('Sam');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable1;
这将产生以下输出-
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | Chris | | 2 | Adam | | 3 | Sam | +----+-----------+ 3 rows in set (0.00 sec)
以下是创建第二个表的查询-
mysql> create table DemoTable2( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2(FirstName) values('John'); mysql> insert into DemoTable2(FirstName) values('Tom'); mysql> insert into DemoTable2(FirstName) values('Bob');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable2;
这将产生以下输出-
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Tom | | 3 | Bob | +----+-----------+ 3 rows in set (0.00 sec)
以下是使用MySQL UNION从两个表中选择的查询-
mysql> (select *from DemoTable1) union (select *from DemoTable2) order by FirstName;
这将产生以下输出-
+----+-----------+ | Id | FirstName | +----+-----------+ | 2 | Adam | | 3 | Bob | | 1 | Chris | | 1 | John | | 3 | Sam | | 2 | Tom | +----+-----------+ 6 rows in set (0.00 sec)