SELECT 语句的查询结果是元组的集合,两个查询的结果可以进行集合操作。集合操作包括并操作 UNION、交操作 INTERSECT 和差操作 EXCEPT。语法格式为:
<查询 1> UNION <查询 2>
<查询 1> INTERSECT <查询 2>
<查询 1> EXCEPT <查询 2>
参加集合操作的<查询 1>和<查询 2>的结果列数和对应列的数据类型必须兼容,值得注意的是集合查询出的结果没有重复元组出现。集合操作可以扩展到多个查询之间,例如:
<查询 1> UNION <查询 2> UNION <查询 3>
例 1.22 查询单价大于 400 或数量大于 3 的订单明细:
select *
from items
where ship_price>400
union
select *
from items
where quantity >3;
查询结果为:
item_num order_num ship_name ship_price quantity
10002 1002 商品 HSK 960.00 2
10004 1003 商品 ANZA 19.80 5
10007 1005 商品 HRR 480.00 5
本查询是求单价大于的订单与数量大于 3 的订单的并集。UNION 执行集合并操作,将多个查询结果合并起来,同时会自动去掉重复的元组。如果想在结果中保留重复元组,则需要使用 UNION ALL 操作符。
例 1.23 查询单价大于 400 且数量大于 3 的订单明细:
select *
from items
where ship_price>400
intersect
select *
from items
where quantity >3;
查询结果为:
item_num order_num ship_name ship_price quantity
10006 1005 商品 HRR 480.00 5
INTERSECT 执行集合交操作,返回多个查询结果中的公共行。
例 1.24 查询单价大于 400 与数量大于 3 的订单明细的差集:
select *
from items
where ship_price>400
except
select *
from items
where quantity >3;
查询结果为:
item_num order_num ship_name ship_price quantity
10002 1002 商品 HSK 960.00 2
本例要求查询单价大于400与数量大于3的订单明细的差集,即查找单价大于400但预订数量小于 3 的订单明细。