[英]Get all entries from Table B which have a relation to multiple entries (given list) from Table A
I have two tables. 我有两张桌子。 Table
A
and Table B
. 表
A
和表B
Both are connected with a many-to-many relationship. 两者都有多对多的关系。
Table A: 表A:
ID
---
1
2
Table B: 表B:
ID
---
3
4
Table AB: 表AB:
ID | A_ID | B_ID
----------------
5 | 1 | 4
6 | 1 | 3
7 | 2 | 3
I want to get the list of ID
s from table B
which have a relation to a list of ID
s of table A
. 我想从表
B
获取ID
列表,这些ID
与表A
的ID
列表有关 。
Example from the above tables: 上表中的示例:
I want to get all B
s which have a relation to table A
ID
1 and ID
2. I get then ID
3 has to both ID
s of table A
. 我想获取所有与表
A
ID
1和ID
2有关系的B
然后,我得到ID
3与表A
两个ID
都有关系。
How could I do this with an SQL query ? 如何使用SQL查询做到这一点?
If you are looking to select based on a list of As (not ALL As), then do it like this: 如果要基于“不作为”列表(而不是“全部”作为)进行选择,请按照以下步骤操作:
SELECT b_id
FROM ab
WHERE a_id IN (1,2)
GROUP BY b_id
HAVING COUNT(a_id) = 2
Replace (1,2)
with your list and 2
in the having clause with the number of list items. 将
(1,2)
替换为您的列表,将hading子句中的2
替换为列表项的数量。
If you get your list of As from a subquery you could do it like that (not in MySQL, though...): 如果从子查询中获得As的列表,则可以这样做(尽管在MySQL中不行,但是...):
WITH subquery (
--subquery code here
)
SELECT b_id
FROM ab
WHERE a_id IN subquery
GROUP BY b_id
HAVING COUNT(a_id) = (SELECT COUNT(*) FROM subquery)
In MySQL you would have to put your subquery code twice and drop the WITH clause. 在MySQL中,您必须将子查询代码放入两次,并删除WITH子句。
You could also use a temporary table, which would then lead to selecting ALL As from that temporary table and thus Gordon Linoffs answer... 您还可以使用一个临时表,这将导致从该临时表中选择“全部为”,因此Gordon Linoffs会回答...
You can do this by joining and counting: 您可以通过加入并计数来做到这一点:
SELECT B_ID
FROM AB JOIN A
ON
AB.A_ID = A.ID
GROUP BY AB.B_ID
HAVING COUNT(DISTINCT AB.A_ID) = (SELECT COUNT(distinct ID) FROM A);
If you know there are no duplicates in AB
or A
, you can remove the distinct
from the count()
. 如果你知道在没有重复
AB
或A
,可以去除distinct
从count()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.