1

非常简单的问题,只是无法解决我的问题。
示例:
3 个表。所有者 <-> OwnerAnimal <-> 动物

动物可以有多个主人,主人可以有多个动物。
现在,给定一个特定的所有者,找到与给定所有者有共同动物的其他所有者。

我认为我们需要多次加入同一张表,如下所示:

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

但我不确定这是否是正确的方法。

4

1 回答 1

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 joina更改为。join

于 2012-12-24T18:37:19.657 回答