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;
執行示例 »