SQL:union \union all、intersect 、except的用法

在SQL中可以使用union \union all 获取并集数据,使用intersect获取交集数据,使用except获取差集数据。

1、数据源准备:

declare @tb1 table (
	TrustId  int
)

declare @tb2 table (
	TrustId int
)

insert into @tb1 
values (1),(2),(3),(4),(5)

insert into @tb2 
values (3),(4),(5),(6)

2、获取交集数据:

select * from @tb1
intersect 
select * from @tb2

查询结果

TrustId
3
4
5

3、获取并集数据。注意union 和union all获取的数据结果的差异。

采用union 进行查询的时候,会有去重处理,而union all没有,所以union 相对union all 而言效率会低一些


---------- use union ----------

select * from @tb1
union 
select * from @tb2

---------- use union all ------

select * from @tb1
union all
select * from @tb2

查询结果:

union union all
11
22
33
44
55
63
 4
 5
 6

4、获取差集:

1)获取只在@tb1中,但不在@tb2中的数据


select * from @tb1
union 
select * from @tb2
except 
select * from @tb2

查询结果:

TrustId
1
2

2)获取只在@tb2中,但不在@tb1中的数据


select * from @tb1
union 
select * from @tb2
except 
select * from @tb1

查询结果:

TrustId
6

在获取差集的时候先union 再except,会更加安全。当然,直接使用except也是没有问题的。

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值