22,182
社区成员




set nocount on
if object_id('表1') is not null
drop table 表1
go
create table 表1([ID] int,[NUM] int)
insert 表1 select '1',2
insert 表1 select '2',3
insert 表1 select '3',4
insert 表1 select '4',5
go
if object_id('表2') is not null
drop table 表2
go
create table 表2([ID] int,[num] int)
insert 表2 select '1',2
insert 表2 select '2',4
insert 表2 select '3',5
insert 表2 select '5',6
go
set nocount off
select
a.id,
a.num as num1,
b.num as num2
from (select * from 表1 t where not exists(select 1 from 表2 where id=t.id and num=t.num)) a
left join (select * from 表2 t where not exists(select 1 from 表1 where id=t.id and num=t.num)) b
on a.id=b.id and a.num<>b.num
/*
id num1 num2
----------- ----------- -----------
2 3 4
3 4 5
4 5 NULL
(3 行受影响)
*/
if object_id('[表1]') is not null drop table [表1]
go
create table [表1]([ID] int,[NUM] int)
insert [表1]
select 1,2 union all
select 2,3 union all
select 3,4 union all
select 4,5
if object_id('[表2]') is not null drop table [表2]
go
create table [表2]([ID] int,[num] int)
insert [表2]
select 1,2 union all
select 2,4 union all
select 3,5 union all
select 5,6
select
a.id,
a.num as num1,
b.num as num2
from 表1 a
left join 表2 b
on a.id=b.id
where not exists(select * from 表2 where id=a.id and num=a.num)
--测试结果:
/*
id num1 num2
----------- ----------- -----------
2 3 4
3 4 5
4 5 NULL
(所影响的行数为 3 行)
*/
select
a.id,
a.num as num1,
b.num as num2
from 表1 a
left join 表2 b
on a.id=b.id and a.num<>b.num
--如果两表的比较都用id列来进行:
select * from tbA where not exists(select 1 from tbB where id=a.id)
但,null值是没法比较的.