在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 |
1 | 1 |
2 | 2 |
3 | 3 |
4 | 4 |
5 | 5 |
6 | 3 |
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也是没有问题的。