Sql简介 专题
专题目录
您的位置:database > Sql简介专题 > SQL Union运算符
SQL Union运算符
作者:--    发布时间:2019-11-20

本教程将演示如何使用sql union组合来自多个查询的两个或多个结果集,并解释unionunion all之间的区别。

1. sql union运算符简介

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的结果:

联合与联接不同,联接组合了多个表的列,而联合组合了表的行。

2. sql union示例

要从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运算符删除了一个重复行。

3. sql union all示例

要保留重复行,请使用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运算符来组合来自不同表的数据。 请参阅以下employeesdependents表:

以下语句使用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运算符组合来自多个查询的两个或多个结果集。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册