表#t1,数据如下:
id code name
1 A001 B001
2 A002 B002
3 A003 B003
5 B005 B005
表#t2,数据如下:
id code name
1 A001 B001
2 A002 B002
3 A003 B003
4 B005 B004
首先#t2.id不能等于#t1.id,在这个基础上,#t2.code和#t2.name不能同时与#t1.code和#t1.name相等,把
#t2的数据取出来,根据上面的例子,#t2的数据是:
id code name
4 B005 B004
假如#t1和#t2的数据如下:
表#t1,数据如下:
id code name
1 A001 B001
2 A002 B002
3 A003 B003
5 B005 B004
表#t2,数据如下:
id code name
1 A001 B001
2 A002 B002
3 A003 B003
4 B005 B004
根据上面写的条件,则#t2的数据是空的,虽然#t1.id=5,而#t2.id=4,两个不相等,但是#t1.code=#t2.code=B005,#t1.name=#t2.name=B004,所以取出的#2的数据为空的。
请问这个SQL语句如何写?谢谢
------解决思路----------------------
with tb1(id,code,name) as
(
select 1 ,'A001','B001' union all
select 2 ,'A002','B002' union all
select 3 ,'A003','B003' union all
select 5 ,'B005','B004'
),
tb2(id,code,name) as
(
select 1 ,'A001','B001' union all
select 2 ,'A002','B002' union all
select 3 ,'A003','B003' union all
select 4 ,'B005','B004'
)
select * from tb2 a where not exists (select * from tb1 where a.id=id) and not exists (select * from tb1 where a.code=code and a.name=name)
------解决思路----------------------
select * from #tb2 a where not exists(select 1 from #tb1 b where a.id=b.id and a.code=b.code and a.name=b.name)
亲测可用