DBAtlas · 数据库运维图谱

UNION / UNION ALL / INTERSECT / EXCEPT(MINUS)

Oracle

-- Union without duplicates
SELECT city FROM customer
UNION
SELECT city FROM supplier;

-- Intersection and difference (MINUS instead of EXCEPT in Oracle)
SELECT city FROM customer INTERSECT SELECT city FROM supplier;
SELECT city FROM customer MINUS SELECT city FROM supplier;

集合运算符合并两个查询的结果集。UNION 去除重复(较慢),UNION ALL 保留全部(较快),INTERSECT 返回共同行,差集运算符返回仅存在于第一个集合中的行。差集方面,Oracle 使用 MINUS 而不是标准的 EXCEPT(自 21c 起也提供 EXCEPT)。

PostgreSQL

SELECT city FROM customer
UNION
SELECT city FROM supplier;

SELECT city FROM customer INTERSECT SELECT city FROM supplier;
SELECT city FROM customer EXCEPT SELECT city FROM supplier;

PostgreSQL 完整支持标准的 UNION、UNION ALL、INTERSECT 和 EXCEPT(差集用 EXCEPT,不是 MINUS)。每个运算符的 ALL 形式(INTERSECT ALL、EXCEPT ALL)会保留重复次数。列数和类型必须兼容。

MySQL

SELECT city FROM customer
UNION
SELECT city FROM supplier;

-- INTERSECT/EXCEPT arrive with MySQL 8.0.31+ and MariaDB 10.3+
SELECT city FROM customer INTERSECT SELECT city FROM supplier;

MySQL 长期以来只支持 UNION / UNION ALL;INTERSECT 和 EXCEPT 直到 MySQL 8.0.31(MariaDB 10.3)才加入。在旧版本中,交集使用 INNER JOIN/EXISTS,差集使用 LEFT JOIN ... IS NULL 或 NOT EXISTS。

SQL Server

SELECT city FROM customer
UNION
SELECT city FROM supplier;

SELECT city FROM customer INTERSECT SELECT city FROM supplier;
SELECT city FROM customer EXCEPT SELECT city FROM supplier;

SQL Server 支持标准的 UNION、UNION ALL、INTERSECT 和 EXCEPT(2005+);差集运算符是 EXCEPT(不是 MINUS)。INTERSECT/EXCEPT 比较行时将 NULL 值视为相等。

MongoDB

// Closest equivalent: $unionWith (MongoDB 4.4+)
db.customer.aggregate([
  { $project: { city: 1, _id: 0 } },
  { $unionWith: { coll: "supplier",
      pipeline: [ { $project: { city: 1, _id: 0 } } ] } },
  { $group: { _id: "$city" } }  // UNION (distinct) effect
])

MongoDB 4.4+ 的 $unionWith 阶段合并两个集合的结果(类似 UNION ALL)。要去除重复,之后用 $group 去重。INTERSECT/EXCEPT 没有直接的等价物;通过 $lookup 或集合运算符($setIntersection、$setDifference)建模。

Redis

# Set operations with the Set data type:
SUNION city_customer city_supplier    # union
SINTER city_customer city_supplier    # intersection
SDIFF  city_customer city_supplier    # difference

Redis 没有 SQL,但 Set 数据类型提供原生集合运算:SUNION(并集)、SINTER(交集)、SDIFF(差集)及其保存结果的 STORE 变体。它们作用于预先构建的集合成员,而不是查询结果。

Elasticsearch

# There is no direct set operator.
# For a union, search multiple indices in one query:
GET customer,supplier/_search
{ "query": { "match_all": {} } }

Elasticsearch 不提供 UNION/INTERSECT/EXCEPT。通过查询多个以逗号分隔的索引可实现并集效果;交集和差集使用 bool 查询的 must/should/must_not 子句,或在应用端进行集合逻辑处理。

在 DBAtlas 中打开 →