[英]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_b,它与表a和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). 现在,我想查询该表,以便获得所有a_id,其中包含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
原因
a_id = 2
没有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... 但是... naaaa ...
what would be a bether solution for this problem? 解决此问题的更好方法是什么?
I think a simpler method is group by
and having
: 我认为更简单的方法是按
group by
并having
:
select a_id
from a_b
where b_id in (1, 2, 3)
group by a_id
having count(*) = 3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.