[英]Querying many-to-many relationship in MySql
可以说我们有这个表a_b,它与表a和b是多对多关系:
+------+------+
| a_id | b_id |
+------+------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
+------+------+
现在,我想查询该表,以便获得所有a_id,其中包含b_id(1、2、3)的条目。 在上面的示例中,输出应为
+------+
| a_id |
+------+
| 1 |
+------+
原因a_id = 2
没有b_id = 3
条目
一种可能的查询是:
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
但是... naaaa ...
解决此问题的更好方法是什么?
我认为更简单的方法是按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.