如图,现在有两个数据集,左边表示#tempTable1,右边表示#tempTable2。现在有以下问题:
1.求两个集的交集?
2.求tempTable1中不属于集#tempTable2的集?
先创建两张临时表:
create table #tempTable1 ( argument1 nvarchar(50), argument2 varchar(20), argument3 datetime, argument4 int ); insert into #tempTable1(argument1,argument2,argument3,argument4) values('preacher001','13023218757',GETDATE()-1,1); insert into #tempTable1(argument1,argument2,argument3,argument4) values('preacher002','23218757',GETDATE()-2,2); insert into #tempTable1(argument1,argument2,argument3,argument4) values('preacher003','13018757',GETDATE()-3,3); insert into #tempTable1(argument1,argument2,argument3,argument4) values('preacher004','13023257',GETDATE()-4,4); insert into #tempTable1(argument1,argument2,argument3,argument4) values('preacher005','13023218',GETDATE()-5,5); insert into #tempTable1(argument1,argument2,argument3,argument4) values('preacher006','13023218',GETDATE()-6,6); insert into #tempTable1(argument1,argument2,argument3,argument4) values('preacher007','13023218',GETDATE()-7,7); insert into #tempTable1(argument1,argument2,argument3,argument4) values('preacher008','13023218',GETDATE()-8,8); create table #tempTable2 ( argument1 nvarchar(50), argument2 varchar(20), argument3 datetime, argument4 int ); insert into #tempTable2(argument1,argument2,argument3,argument4) values('preacher001','13023218757',GETDATE()-1,1); insert into #tempTable2(argument1,argument2,argument3,argument4) values('preacher0010','23218757',GETDATE()-10,10); insert into #tempTable2(argument1,argument2,argument3,argument4) values('preacher003','13018757',GETDATE()-3,3); insert into #tempTable2(argument1,argument2,argument3,argument4) values('preacher004','13023257',GETDATE()-4,4); insert into #tempTable2(argument1,argument2,argument3,argument4) values('preacher009','13023218',GETDATE()-9,9);
比如,我现在以#tempTable1和#tempTable2的argument1作为参照
1.求两集的交集:
1)in 方式
select * from #tempTable2 where argument1 in (select argument1 from #tempTable1)
2)exists 方式
select * from #tempTable2 t2 where exists (select * from #tempTable1 t1 where t1.argument1=t2.argument1)
2.求tempTable1中不属于集#tempTable2的集
1)in 方式
select * from #tempTable1 where argument1 not in (select argument1 from #tempTable2)
2)exists 方式
select * from #tempTable1 t1 where not exists (select * from #tempTable2 t2 where t1.argument1=t2.argument1)