SQL集合运算(并、交、差)和空值

本文介绍了SQL中的集合运算union、intersect和except的基本概念,展示了如何使用它们进行数据合并,并强调了空值处理规则,包括算术运算中的unknown状态和isnull/isnotnull的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

集合运算

unionintersectexcept对应于∪、∩、-运算

并运算union

union自动去除重复,如果想保留所有重复,则用union all代替union

(select course_id
from section
where semester = 'Fall' and year = 2009)
union
(select course_id
from section
where semester = 'Spring' and year = 2010)
交运算intersect

intersect自动去除重复,如果想保留所有重复,则用intersect all代替intersect

(select course_id
from section
where semester = 'Fall' and year = 2009)
intersect
(select course_id
from section
where semester = 'Spring' and year = 2010)
差运算except/minus

except在操作前自动去除输入重复,如果想保留所有重复,则用except all代替except

(select course_id
from section
where semester = 'Fall' and year = 2009)
except
(select course_id
from section
where semester = 'Spring' and year = 2010)

也可以使用minus

select *
from sc
where cno='003'
minus
select *
from sc
where grade<60;

空值

  • 算术运算中,如果算术表达式的任一输入为空,则该算术表达式(+、-、*、/)结果为空
  • SQL将涉及空值的任何比较运算结果视为unknown,这是truefalse之外的第三个逻辑值
  • and or not布尔运算中,只有true or unknown结果为true,其他涉及unknown的布尔运算结果都为unknown
  • 如果where子句计算出falseunknown,都不会被加入到结果集中
  • is null试空值,结果为trueis not null,则为false
  • 某些SQL还允许使用is unknownis not unknown来测试一个表达式的结果是否为unknown
  • 比较两个元组对应属性值时,都是null,那么判断上是相同的,这与比较运算null = null 结果为unknown不一样
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值