Pretty simple question, just cannot wrap my head around it.
Example:
3 tables. Owner <-> OwnerAnimal <-> Animal
Animal can have multiple owners, and owner can have multiple animals.
Now, given a specific owner, find other owners that have animals in common with the given owner.
What I think is that we need to do join on the same table multiple times, like this:
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
But I’m not sure if this is a right approach.
If you want any overlap of animals, the following is the way that I think of it:
You can rewrite this as a join, but the
inseems to make more sense.If you want all animals to be the same, then you need to do a join.
The idea is to do a set comparison using the
havingclause. The first subclause guarantees that the number of animals for the second owner is the same as the number for 100. The second guarantees that there is no animal owned by the second owner that is not owned by the original owner. Theleft outer joinkeeps all animals.The use of the
distinctkeyword is for the situations where an animal could appear twice for an owner. It is unclear whether this is allowed.If you want owners that own the same animals as the original owner, but could own others, then change the
left outer jointo ajoinin the previous query.