PostgreSQL UNION 操作符
并集
UNION
操作符用于合并两个或多个查询的结果集。
UNION 中的查询必须遵循以下规则:
- 它们必须具有相同数量的列。
- 列必须具有相同的数据类型。
- 列必须以相同的顺序出现。
示例
使用 UNION
操作符合并 products
表和 testproducts
表。
SELECT product_id, product_name
FROM products
并集
SELECT testproduct_id, product_name
FROM testproducts
ORDER BY product_id;
运行示例 »
UNION 与 UNION ALL 的区别
使用 UNION
操作符时,如果两个查询返回的某些行结果完全相同,则只显示一行,因为 UNION
只选择不同的值。
使用 UNION ALL
返回重复值。
让我们对查询进行一些更改,以便结果中出现重复值。
示例 - UNION
SELECT product_id
FROM products
并集
SELECT testproduct_id
FROM testproducts
ORDER BY product_id;
运行示例 »
示例 - UNION ALL
SELECT product_id
FROM products
UNION ALL
SELECT testproduct_id
FROM testproducts
ORDER BY product_id;
运行示例 »