急!这样的SQL语句能查询出结果吗?

cfqmxh 2005-04-07 01:54:25
我准备找出两个表中不同的数据,这两个表的结构完全相同,如:
表1:Table1
id a b c
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
表2:Table2
id a b c
1 1 1 2
2 2 2 1
3 3 3 3
4 4 4 4
6 6 6 6
我要得到两个表互不相同的记录的id值,如上面的结果为:
id a b c
1 1 1 1
2 2 2 2
5 5 5 5
6 6 6 6
只需要得到id的值为:1,2,5,6即可!

select id,a,b,c into ##1 from Table1 where id
not in(select id from Table2)
and a not in(select a from Table2)
and b not in(select b from Table2)
and c not in(select c from Table2)

select id,a,b,c into ##2 from Table2 where id
not in(select id from Table1)
and a not in(select a from Table1)
and b not in(select b from Table1)
and c not in(select c from Table1)

select * into ##3 from ##1 union (select * from ##2)
select distinct(id) from ##3
这样怎么不行呀!

...全文
88 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
rocklabzhang 2005-04-07
  • 打赏
  • 举报
回复
create table Table1
(
id int,
a int,
b int,
c int
)

create table Table2
(
id int,
a int,
b int,
c int
)

insert into Table1
select 1,1,1,1
union all
select 2,2,2,2
union all
select 3,3,3,3
union all
select 4,4,4,4
union all
select 5,5,5,5

insert into Table2
select 1,1,1,2
union all
select 2,2,2,1
union all
select 3,3,3,3
union all
select 4,4,4,4
union all
select 6,6,6,6

select id from Table1 where id not in ( select id from Table2 )
union all
select id from Table2 where id not in ( select id from Table1 )
union all
select T1.id from Table1 T1, Table2 T2 where T1.id=T2.id and ( T1.a<>T2.a or T1.b<>T2.b or T1.c <> T2.c )

drop table Table1
drop table Table2
cfqmxh 2005-04-07
  • 打赏
  • 举报
回复
行了!
非常感谢zjcxc(邹建)大哥!
结贴.
zjcxc 元老 2005-04-07
  • 打赏
  • 举报
回复
--测试数据
create table Table1(id int,a int,b int,c int)
insert Table1 select 1,1,1,1
union all select 2,2,2,2
union all select 3,3,3,3
union all select 4,4,4,4
union all select 5,5,5,5

create table Table2(id int,a int,b int,c int)
insert Table2 select 1,1,1,2
union all select 2,2,2,1
union all select 3,3,3,3
union all select 4,4,4,4
union all select 6,6,6,6
go

--查询
select distinct
isnull(a.id,b.id) as id
from table1 a full join table2 b
on a.id=b.id
where a.id is null
or b.id is null
or a.a<>b.a
or a.b<>b.b
or a.c<>b.c
go

--删除测试
drop table table1,table2

/*--结果
id
-----------
1
2
5
6

(所影响的行数为 4 行)
--*/
zjcxc 元老 2005-04-07
  • 打赏
  • 举报
回复
select distinct
isnull(a.id,b.id) as id
from table1 a full join table2 b
on a.id=b.id
where a.id is null
or b.id is null
or a.a<>b.a
or a.b<>b.b
or a.c<>b.c
zjcxc 元老 2005-04-07
  • 打赏
  • 举报
回复
select distinct
isnull(a.id,b.id) as id
from table1 a full join table2 b
on a.id=b.id and a.a=b.a and a.b=b.b and a.c=b.c
where a.id is null
or b.id is null
or a.a<>b.a
or a.b<>b.b
or a.c<>b.c

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧