Reputation: 6301
lets say we have this table a_b, which is a many-to-many-relationship with table a and b:
+------+------+
| a_id | b_id |
+------+------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
+------+------+
Now i want to query this table, so that i get all a_ids, which have a entry for b_id (1, 2, 3). In the above example, the output should be
+------+
| a_id |
+------+
| 1 |
+------+
cause a_id = 2
has no entry for b_id = 3
one possible query would be:
select *
from a
join a_b as a_b1
on a_b1.a_id = a.id and a_b1.b_id = 1
join a_b as a_b2
on a_b2.a_id = a.id and a_b2.b_id = 2
join a_b as a_b3
on a_b3.a_id = a.id and a_b3.b_id = 3
but... naaaa...
what would be a bether solution for this problem?
Upvotes: 0
Views: 41
Reputation: 1269503
I think a simpler method is group by
and having
:
select a_id
from a_b
where b_id in (1, 2, 3)
group by a_id
having count(*) = 3;
Upvotes: 2