2012-12-24 12 views
1

很简单的问题,只是无法将我的头围绕它。例如:
3表。所有者< - >所有者动物< - >动物查找是否存在多个交叉点

动物可以有多个所有者,并且所有者可以拥有多个动物。
现在,给定具体所有者,找到与给定所有者具有共同动物的其他所有者。

我想的是,我们需要做在同一个表中多次加入,就像这样:

select distinct 
o2.Owner_Id, 
o2.Name 
from Owner o 
left join OwnerAnimal oa 
on o.Owner_Id = oa.Owner_Id 
left join OwnerAnimal oa2 
on oa.Animal_id = oa2.Animal_Id 
left join Owner o2 
on. oa2.Owner_Id = o2.Animal_Id 
Where o.Owner_Id = 100 and o2.Owner_Id <> 100 --To exclude current owner from the list 

但我不知道这是否是一个正确的做法。

回答

2

如果您想要动物的任何重叠,以下是我认为它的方式:

select distinct ao.owner 
from AnimalOwners ao 
where ao.animal in (select animal from AnimalOwners ao1 and ao1.owner = 100) and 
     ao.owner <> 100 

您也可以重写此为连接,但in似乎更有意义。

如果你想要所有的动物是相同的,那么你需要做一个加入。

with a as (select distinct animal from AnimalOwners where ao.owner = 100) 
select ao.owner 
from AnimalOwners ao left outer join 
    a 
    on ao.animal = a.animal 
where ao.owner <> 100 
group by ao.owner 
having count(disinct ao.animal) = (select count(*) from a) and 
     count(*) = count(a.animal) 

的想法是做使用having第一套比较。第一个条款保证第二个所有者的动物数量与100的数量相同。第二个条款保证第二个所有者拥有的不是原始所有者所有的动物。 left outer join保留所有动物。

distinct关键字的使用适用于动物可能出现两次所有者的情况。目前尚不清楚这是否允许。

如果您想拥有与原始拥有者相同动物但拥有其他拥有者的所有者,则可以在前面的查询中将left outer join更改为join

+0

这很好。目前,第一种解决方案对我来说已经足够了。我刚刚为业主添加了一个额外的连接来提取其他字段。非常感谢! – user194076