PostgreSQL UNION 运算符
UNION
UNION 运算符用于组合两个或多个查询的结果集。
在 UNION 中的查询必须遵循以下规则:
- 它们必须具有相同的列数
- 列必须具有相同的数据类型
- 列的顺序必须相同
实例
使用 UNION 运算符合并 products 和 testproducts:
SELECT product_id, product_name FROM products UNION SELECT testproduct_id, product_name FROM testproducts ORDER BY product_id;
UNION 与 UNION ALL
对于 UNION 操作符,如果两个查询中的某些行返回完全相同的结果,则只会列出一行,因为 UNION 仅选择不同的值。
使用 UNION ALL 返回重复值。
让我们对查询进行一些更改,以便结果中有重复的值:
实例 - UNION
SELECT product_id FROM products UNION 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;