读书人

两表查询出不相等的记录这个语句该如

发布时间: 2012-02-03 22:02:47 作者: rapoo

两表查询出不相等的记录,这个语句该怎么写呢?

表TestA 记录如下:
itemcode Kind
A A01
B B01
C C01
表TestB 记录如下:
itemcode Kind
A A01
B B01
B B02
请选出itemcode在表TestA中存在但在TestB中不存在以及itemcode在表TestA中存在在TestB中也存在,但相同itemcode在TestA中存在但在TestB中不存在的所有记录。
请教各位这个SQL语句该如何写呢?谢谢!

[解决办法]
不是全明白.
a中存在b中不存在的:
select * from TestA a where not exists(select 1 from TestB where itemcode <> a.itemcode)

两者都存在的:
select * from TestA Inner Join TestB On TestA.itemcode=TestB.itemcode


[解决办法]
"请选出itemcode在表 "
-----------------------
itemcode是个变量的值吗?还是比较TestA中有,但TestB中没有的记录(通过itemcode关联)?
[解决办法]
LZ的问题 在下是:不是全明白 也不是全不明白~有些不明白,还有些真明白.

全部存在
select * from TestA Inner join TestB on TestA.itemcode=TestB.itemcode
有一个不存在
select * from TestA
where not exists(select 1 from TestA Inner Join TestB on TestA.itemcode=TestB.itemcode)
[解决办法]
逻辑有点乱
--查TestA中有,但不在TestB中的
select * from TestA
where itemcode not in (select itemcode from TestB )

--查TestB中有,但不在TestA中的
select * from TestB
where itemcode not in (select itemcode from TestA )

--全部存在
select * from TestA,TestB where TestA.itemcode=TestB.itemcode

--相同itemcode在TestA中存在但在TestB中不存在的所有记录
select b.* from TestA b left join
(select itemcode,count(*)from TestA group by itemcode having(count(*)> =2))a
on b.itemcode=a.itemcode
where b.itemcode not in(select item_code from TestB )



[解决办法]
itemcode在表TestA中存在但在TestB中不存在
select * from testa a
where not exists(select * from testb where a.itemcode=itemcode)

itemcode在表TestA中存在在TestB中也存在
select * from testa a
where exists(select * from testb where a.itemcode=itemcode)

[解决办法]
--感觉是这个意思吧,楼主

create table TestA (itemcode char(1),kind char(3))
create table TestB (itemcode char(1),kind char(3))

insert TestA values ( 'A ', 'A01 ')
insert TestA values ( 'B ', 'B01 ')
insert TestA values ( 'C ', 'C01 ')

insert TestB values ( 'A ', 'A01 ')
insert TestB values ( 'B ', 'B01 ')
insert TestB values ( 'B ', 'B02 ')


select a.itemcode ,case when exists(select 1 from TestA where itemcode = a.itemcode ) and exists(select 1 from TestB where itemcode = a.itemcode) then '1.均有 '
when exists(select 1 from TestA where itemcode = a.itemcode ) and (not exists(select 1 from TestB where itemcode = a.itemcode)) then '2.A有,B无 '
when (not exists(select 1 from TestA where itemcode = a.itemcode )) and exists(select 1 from TestB where itemcode = a.itemcode) then '3.A无,B有 '
when (not exists(select 1 from TestA where itemcode = a.itemcode )) and (not exists(select 1 from TestB where itemcode = a.itemcode)) then '4.均无 ' end


from
(select distinct(itemcode) from TestA
union
select distinct(itemcode) from TestB) a

drop table TestA
drop table TestB


[解决办法]
select * from testa where not exists (
select 1 from testb where itemcode=testa.itemcode and Kind=testa.Kind
)
union all
select * from testb where not exists (
select 1 from testa where itemcode=testb.itemcode and Kind=testb.Kind
)

读书人网 >SQL Server

热点推荐