Get all entries from Table B which have a relation to multiple entries (given list) from Table A

一个人想着一个人 提交于 2019-12-19 11:23:04

问题


I have two tables. Table A and Table B. Both are connected with a many-to-many relationship.

Table A:

ID
---
1
2

Table B:

ID
---
3
4

Table AB:

ID | A_ID | B_ID
----------------
5  | 1    | 4
6  | 1    | 3
7  | 2    | 3

I want to get the list of IDs from table B which have a relation to a list of IDs of table A.

Example from the above tables:

I want to get all Bs which have a relation to table A ID 1 and ID 2. I get then ID 3 has to both IDs of table A.

How could I do this with an SQL query ?


回答1:


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.

If you get your list of As from a subquery you could do it like that (not in MySQL, though...):

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.

You could also use a temporary table, which would then lead to selecting ALL As from that temporary table and thus Gordon Linoffs answer...




回答2:


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().



来源:https://stackoverflow.com/questions/26650786/get-all-entries-from-table-b-which-have-a-relation-to-multiple-entries-given-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!