I am trying to find an efficient query to find all matching objects in a "join" table.
Given an object Adopter
that has many Pets
, and Pets
that have many Adopters
through a AdopterPets
join table. How could I find all of the Adopters
that have the same Pets
?
The schema is fairly normalized and looks like this.
TABLE Adopter
INTEGER id
TABLE AdopterPets
INTEGER adopter_id
INTEGER pet_id
TABLE Pets
INTEGER id
Right now the solution I am using loops through all Adopters
and asks for their pets anytime it we have a match store it away and can use it later, but I am sure there has to be a better way using SQL.
One SQL solution I looked at was GROUP BY
but it did not seem to be the right trick for this problem.
EDIT
To explain a little more of what I am looking for I will try to give an example.
+---------+ +------------------+ +------+
| Adptors | | AdptorsPets | | Pets |
|---------| +----------+-------+ |------|
| 1 | |adptor_id | pet_id| | 1 |
| 2 | +------------------+ | 2 |
| 3 | |1 | 1 | | 3 |
+---------+ |2 | 1 | +------+
|1 | 2 |
|3 | 1 |
|3 | 2 |
|2 | 3 |
+------------------+
When you asked the Adopter
with the id
of 1
for any other Adopters
that have the same Pets
you would be retured id 3
.
If you asked the same question for the Adopter
with the id
of 3
you would get id 1
.
If you asked again the same question of the Adopter with
id 2` you would be returned nothing.
I hope this helps clear things up!