集合操作
SQL 集合操作将多个查询块的结果合并为一个结果。 SQL 标准定义了以下三种集合操作: UNION
,INTERSECT
,EXCEPT
,UNION ALL
,INTERSECT ALL
,EXCEPT ALL
。
并集 (Union)
将来自两个查询块的所有结果合并为一个结果,省略重复项。
获取来自 customers 和 users 表的所有名称,排除重复项。
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
并集全部 (Union All)
将来自两个查询块的所有结果合并为一个结果,包括重复项。
假设您有两个表,一个表示在线销售,另一个表示实体店销售。在这种情况下,您希望将两个表的数据合并为一个结果集。由于可能存在重复交易,您希望保留所有记录而不消除重复项。
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
交集 (Intersect)
仅合并两个查询块结果中共有的行,省略重复项。
假设您有两个存储有关学生课程选修信息的表。您想找到两个不同部门之间共有的课程,
但您希望得到不同的课程名称,并且不考虑相同学生多次选修同一门课程。
在这种情况下,您希望找到两个部门之间共有的课程,但不想多次计数相同课程,即使同一部门的多个学生都选修了它。
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
交集全部 (Intersect All)
仅合并两个查询块结果中共有的行,包括重复项。
假设您有两个包含客户订单数据的表,并且您想要确定普通客户和 VIP 客户都订购的产品。在这种情况下,您希望跟踪每个产品的数量,即使不同客户多次订购同一产品。
在这种情况下,您希望找到普通客户和 VIP 客户都订购的产品,但您希望保留数量信息,即使相同产品被不同客户多次订购。
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
差集 (Except)
对于两个查询块 A 和 B,返回 A 中独有的结果,即不包含在 B 中的结果,省略重复项。
假设您有两个存储员工项目分配信息的表。您想找到仅属于一个部门且与另一个部门不共享的项目,排除重复项。
在这种情况下,您想要确定仅属于一个部门且与另一个部门不共享的项目。您不想多次计数相同的项目,
即使同一部门的多个员工被分配到它。
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts
差集全部 (Except All)
对于两个查询块 A 和 B,返回 A 中独有的结果,即不包含在 B 中的结果,包括重复项。
假设您有两个包含客户订单数据的表,并且您想要确定仅由普通客户(没有 VIP 客户)订购的产品。在这种情况下,您希望跟踪每个产品的数量,即使不同普通客户多次订购同一产品。
在这种情况下,您想要找到仅由普通客户订购(没有 VIP 客户订购)的产品。您希望保留数量信息,即使不同普通客户多次订购同一产品。
import-pattern
builder-pattern
schema.ts
import-pattern
builder-pattern
schema.ts