簡體   English   中英

在MySql中查詢多對多關系

[英]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 byhaving

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM