GaussDB union 的用法

发布于:2025-07-23 ⋅ 阅读:(24) ⋅ 点赞:(0)

1 union 的作用


union 运算符用于组合两个或更多 select 语句的结果集。


2 union 使用前提


union 中的每个 select 语句必须具有相同的列数

  • 这些列也必须具有相似的数据类型
  • 每个 select 语句中的列也必须以相同的顺序排列

3 union 语法


select column_name(s) from table1
union
select column_name(s) from table2;
注释:默认情况下,union 运算符选择一个不同的值。如果允许重复值,请使用union all。

4 UNION ALL 语法

select column_name(s) from table1
union all
select column_name(s) from table2;
注释:UNION 结果集中的列名总是等于 UNION 中第一个 select 语句中的列 名。

5 示例数据


以下是"customers" 表中的数据:
csdn=> select * from customers;
 id |  name  |     addr      | city |  zip   | province
----+--------+---------------+------+--------+----------
  1 | 鲁智深 | 北京路27号    | 平凉 | 200000 | 甘肃省
  2 | 李四   | 南京路12号    | 杭州 | 310000 | 浙江市
  3 | 王五   | 花城大道17号  | 广州 | 510000 | 广州省
  4 | 马六   | 江夏路19号    | 武汉 | 430000 | 湖北省
  5 | 赵七   | 西二旗12号    | 北京 | 100000 | 北京市
  6 | 宋一   | 花城大道21号  | 广州 | 510000 | 广东省
  7 | 刘二   | 长安街 121 号 | 北京 | 100000 | 北京市
  8 | 宋江   | 梁山路1号     | 济南 | 250000 | 山东省
    | 武松   |               | 邢台 |        | 河北省
 10 | 韩信   | 梁山路1号     | 渝东 | 250001 | 四川省
 11 | 吕不韦 | 梁山路1号     | 渝中 | 250001 | 四川省
(11 rows)

csdn=>

选自 "suppliers" 表的数据:

csdn=> select * from suppliers;
 id |   name   |     addr     | city |  zip   | province
----+----------+--------------+------+--------+----------
  1 | 沃尔玛   | 北京路35号   | 上海 | 200000 | 上海市
  2 | 家乐福   | 玄武街28号   | 南京 | 210000 | 江苏省
  3 | 永旺超市 | 花城大道21号 | 广州 | 710000 | 广东省
  4 | 宋江超市 | 梁山路1号    | 济南 | 250000 | 山东省
(4 rows)

csdn=>

6 union 举证


以下 sql 语句从 "customers" 和"suppliers" 表中选择所有不同的城市(只有不同的值):

select city from customers
union
select city from suppliers;

结果:

注:

不能用 union来列出两个表中的所有城市。如果一些客户和供应商来自同一个城市,每个城市将只被列入一个列表。union 将只选择不同的值,即会排除重复数据只保留一个。请使用 union all 选择重复值!

7 union all 实例


以下 sql语句使用union all 从 "customers"和"suppliers" 表中选择所有城市(也是重复的值):

select city as "城市" from customers
union all
select city from suppliers;

结果:
 

8 带有 where 的 union all


以下 sql 语句使用 unionall 从"customers"和 "suppliers" 表中选择所有上海市的城市(也是重复数值):

举例:

select city as "城市", province as "省份" from customers
where province='广东省'
union all
select city, province from suppliers
where province='广东省';

结果:

9 带有 where 的union


以下 sql 语句从"客户"和"供应商"中选择所有不同的上海城市(只有不同的值):
 

select city as "城市", province as "省份" from customers
where province='广东省'
union
select city, province from suppliers
where province='广东省';


结果:

10 批注


union 就是将多段功能类似的 sql 连接起来,并且可以去掉重复的行,有distinct 的功能。union all 则只是单纯的将多段类似 sql 连接起来,而且他们的好处是可以将复杂 sql 按不同的功能或作用拆分成一小段 sql 进行拼接,可以有效提高查询效率。


网站公告

今日签到

点亮在社区的每一天
去签到