select * from a where not exists(select 1 from b where a.省=b.省 and a.城市=b.城市)
select * from a where not exists(select 1 from b where 省 = a.省 and 城市 = a.城市)
create table a(省 varchar(10), 城市 varchar(10)) insert into a values('浙江' , '杭州') insert into a values('浙江' , '宁波') insert into a values('浙江' , '舟山') insert into a values('湖南' , '长沙') create table b(省 varchar(10), 城市 varchar(10)) insert into b values('浙江' , '杭州') insert into b values('湖南' , '长沙') goselect * from a where not exists(select 1 from b where 省 = a.省 and 城市 = a.城市)drop table a, b/* 省 城市 ---------- ---------- 浙江 宁波 浙江 舟山(所影响的行数为 2 行) */
select * from a where not exists(select 1 from b where 省 is not null and 城市 is not null and 省 = a.省 and 城市 = a.城市) and 省 is not null and 城市 is not null
--> 测试数据: @a declare @a table (省 varchar(4),城市 varchar(4)) insert into @a select '浙江','杭州' union all select '浙江','宁波' union all select '浙江','舟山' union all select '湖南','长沙' union all select '湖南',null union all select '湖北','' union all select '广州',null --> 测试数据: @b declare @b table (省 varchar(4),城市 varchar(4)) insert into @b select '浙江','杭州' union all select '湖南','长沙' union all select '广州',nullselect * from @a a where not exists(select 1 from @b where isnull(省,'')=isnull(a.省,'') and isnull(城市,'')=isnull(a.城市,''))--结果: 省 城市 ---- ---- 浙江 宁波 浙江 舟山 湖南 NULL 湖北
except
select * from b
select * from a where not exists(select 1 from b where a.省=b.省 and a.城市=b.城市)
insert into a values('浙江' , '杭州')
insert into a values('浙江' , '宁波')
insert into a values('浙江' , '舟山')
insert into a values('湖南' , '长沙')
create table b(省 varchar(10), 城市 varchar(10))
insert into b values('浙江' , '杭州')
insert into b values('湖南' , '长沙')
goselect * from a where not exists(select 1 from b where 省 = a.省 and 城市 = a.城市)drop table a, b/*
省 城市
---------- ----------
浙江 宁波
浙江 舟山(所影响的行数为 2 行)
*/
select * from a where not exists(select 1 from b where 省 is not null and 城市 is not null and 省 = a.省 and 城市 = a.城市) and 省 is not null and 城市 is not null
表b(省,城市)
a
省 城市
浙江 杭州
浙江 宁波
浙江 舟山
湖南 长沙
湖南 null
湖北
广州 null
b
省 城市
浙江 杭州
湖南 长沙
广州 null现要求找出,a中有,b中没有的记录
浙江 宁波
浙江 舟山
湖南 null
湖北》》》》》》》》》》
能实现这样的吗
declare @a table (省 varchar(4),城市 varchar(4))
insert into @a
select '浙江','杭州' union all
select '浙江','宁波' union all
select '浙江','舟山' union all
select '湖南','长沙' union all
select '湖南',null union all
select '湖北','' union all
select '广州',null
--> 测试数据: @b
declare @b table (省 varchar(4),城市 varchar(4))
insert into @b
select '浙江','杭州' union all
select '湖南','长沙' union all
select '广州',nullselect * from @a a where not exists(select 1 from @b where isnull(省,'')=isnull(a.省,'') and isnull(城市,'')=isnull(a.城市,''))--结果:
省 城市
---- ----
浙江 宁波
浙江 舟山
湖南 NULL
湖北