本教程将演示如何使用sql union
组合来自多个查询的两个或多个结果集,并解释union
和union all
之间的区别。
union
运算符将两个或多个select语句的结果集合并到一个结果集中。 以下语句说明了如何使用union
运算符组合两个查询的结果集:
select
column1, column2
from
table1
union [all]
select
column3, column4
from
table2;
要使用union
运算符,可以编写单独的select
语句,并通过关键字union
将它们连接起来。
select
语句返回的列必须具有相同或可转换的数据类型,大小和相同的顺序。
数据库系统首先执行两个select
语句来处理查询。 然后,它将两个单独的结果集合并为一个,并消除重复的行。 为了消除重复的行,数据库系统对每列的组合结果进行排序,并扫描它以查找彼此相邻的匹配行。
要保留结果集中的重复行,请使用union all
运算符。
假设我们有两个结果集a(1,2)
和b(2,3)
。 下图说明了a union b
结果:
以下图片说明了a union all b
的结果:
联合与联接不同,联接组合了多个表的列,而联合组合了表的行。
要从a
表中获取数据,请使用以下select
语句:
select
id
from
a;
执行上面查询语句,得到以下结果:
select
id
from
a;
要从b
表中检索数据,请使用以下语句:
mysql> select
id
from
b;
+----+
| id |
+----+
| 2 |
| 3 |
+----+
2 rows in set
要组合这两个查询的结果集,请使用union
运算符,如下所示:
select
id
from
a
union
select
id
from
b;
执行上面查询语句,得到以下结果:
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
3 rows in set
结果集仅包含3
行,因为union
运算符删除了一个重复行。
要保留重复行,请使用union all
运算符,如下所示:
select
id
from
a
union all
select
id
from
b;
执行上面查询语句,得到以下结果:
+----+
| id |
+----+
| 1 |
| 2 |
| 2 |
| 3 |
+----+
4 rows in set
4. sql union带有order by示例
要对结果集进行排序,请在所有select
语句之后放置order by
子句,如下所示:
select
id
from
a
union
select
id
from
b
order by id desc;
执行上面查询语句,得到以下结果:
+----+
| id |
+----+
| 3 |
| 2 |
| 1 |
+----+
3 rows in set
数据库系统执行以下步骤:
select
语句。order by
子句中指定的列对组合结果集进行排序。实际上,我们经常使用union
运算符来组合来自不同表的数据。 请参阅以下employees
和dependents
表:
以下语句使用union
运算符组合员工和受抚养人的名字和姓氏。
select
first_name,
last_name
from
employees
union
select
first_name,
last_name
from
dependents
order by
last_name;
执行上面查询语句,得到以下结果:
+------------+-----------+
| first_name | last_name |
+------------+-----------+
| grace | chen |
| dan | chen |
| daniel | chen |
| matthew | chen |
| john | chen |
| valli | chen |
| diana | chen |
| helen | chen |
| nancy | chen |
| karl | chen |
| matthew | han |
.....
| guy | zhang |
| karen | zhang |
| ed | zhao |
| britney | zhao |
| jennifer | zhao |
| susan | zhou |
| uma | zhou |
| bob | zhou |
| lucille | zhou |
| michael | zhou |
| pat | zhou |
+------------+-----------+
70 rows in set
在本教程中,您学习了如何使用union
运算符组合来自多个查询的两个或多个结果集。