简体   繁体   中英

Querying many-to-many relationship in MySql

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM