可以说我们有这个表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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句