结合多个高级MySQL选择查询的最佳方法?
要组合多个高级MySQL选择查询,请使用UNION。让我们首先创建一个表-
mysql> create table DemoTable1 (Value1 int,Value2 int);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1 values(10,29); mysql> insert into DemoTable1 values(100,190); mysql> insert into DemoTable1 values(40,101);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable1;
这将产生以下输出-
+--------+--------+ | Value1 | Value2 | +--------+--------+ | 10 | 29 | | 100 | 190 | | 40 | 101 | +--------+--------+ 3 rows in set (0.00 sec)
以下是创建第二个表的查询-
mysql> create table DemoTable2 (Number1 int, Number2 int);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2 values(100,290); mysql> insert into DemoTable2 values(200,390); mysql> insert into DemoTable2 values(50,170);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable2;
这将产生以下输出-
+---------+---------+ | Number1 | Number2 | +---------+---------+ | 100 | 290 | | 200 | 390 | | 50 | 170 | +---------+---------+ 3 rows in set (0.00 sec)
以下是结合多个高级MySQL选择查询的查询-
mysql> (select Value1,Value2 from DemoTable1) union (select Number1 AS Value1, Number2 AS Value2 from DemoTable2) order by Value1 DESC;
这将产生以下输出-
+--------+--------+ | Value1 | Value2 | +--------+--------+ | 200 | 390 | | 100 | 290 | | 100 | 190 | | 50 | 170 | | 40 | 101 | | 10 | 29 | +--------+--------+ 6 rows in set (0.04 sec)