SQL server 2012之数据查询(4)— 集合查询

select语句的查询结果是元组的集合,所以多个select语句的结果可进行集合操作。
集合操作主要包括:

  • 并操作 union
  • 交操作 intersect
  • 差操作 except

这里需要注意的是:参加集合操作的各查询结果的列数的列数必须相同,对应项的数据类型也必须相同

1.并操作union的使用

例1、 查询计算机科学系(cs)的学生及年龄不大于19岁的学生

方法1select *
	from student
	where sdept = 'cs'
	union
	select *
	from student 
	where sage <= 19

或者
方法2select distinct *  //去掉重复的列
	from student
	where sdept = 'cs' or sage<=19

解释:本查询实际上是求计算机科学系的所有学生及年龄不大于19岁的学生的并集。使用union将多个查询结果合并起来时,系统会自动去掉重复元组。
使用union all 将多个查询结果合并起来,保留重复元组,包括空值。

例2、 查询选修了课程1或者选修了课程2的学生

select *
from sc
where cno = '1'
union
select *
from sc
where cno = '2'

2.交操作intersect的使用

例3、 查询计算机科学系(cs)的学生与年龄不大于19岁的学生的交集

方法1select *
	from student 
	where sdept = 'cs'
	intersect 
	select *
	from student 
	where sage <= 19

或者
方法2select distinct *
	from student
	where sdept = 'cs' and sage <= 19

3.差操作except的使用

例4、 查询计算机科学系(cs)的学生与年龄不大于19岁的学生的差集。

方法1select *
	from student 
	where sdept = 'cs'
	except
	select *
	from student 
	where sage <= 19
//等价于:cs系的年龄大于19岁的学生(如方法2)
或者
方法2select *
from student
where sdept = 'cs' and sage > 19
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值