Sunday, February 19, 2012

Help: Find the different records from 3 tables

I have 3 tables a , ab and b. table ab is the maping table between a
and b. table a contains multiple atid for aid. Same as table b. Now I
want find those aid and bid that contains different atid or btid.
please see the following scripts:
create table a
(aid int, atid int)
create table b
(bid int, btid int)
create table ab
(aid int, bid int)
insert into ab
values(1,1)
insert into ab
values(2,2)
insert into ab
values(3,3)
insert into ab
values(4,4)
insert into a
values(1,1)
insert into a
values(1,2)
insert into a
values(2,5)
insert into a
values(3,3)
insert into a
values(3,4)
insert into a
values(4,7)
insert into b
values(1,1)
insert into b
values(1,2)
insert into b
values(2,5)
insert into b
values(3,3)
insert into b
values(3,7)
insert into b
values(4,6)
I want get 3 and 4 .
because aid 1 contains (1,2) which is same as bid 1
aid 2 contain (5) which is same as bid 2
aid 3 contains (3,4) which is DIFF with bid 3 which contains(3,7)
aid 4 contains (7) which is DIFF with bid 4 which contains(6)
but if I execute the following I get 4 only, because one record (3, 3)
is satify the where condition.
select * from
ab
where ab.aid not in(
select a.aid from
a inner join ab on a.aid = ab.aid
inner join b on ab.bid = b.bid
where a.atid = b.btid
)
help pleaseselect distinct aid from(
select aid, count(*) cnt from(
select aid, atid from a
union all
select aid, btid atid from ab join b on ab.bid=b.bid
) t
group by aid, atid
having count(*)=1
) t|||select distinct ab.aid
from ab join a on ab.aid=a.aid
full outer join b on ab.bid=b.bid and a.atid=b.btid
where (a.aid is null or b.bid is null)
and ab.aid is not null|||Excellent, Thank you!!

No comments:

Post a Comment