简体   繁体   中英

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 . 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 ID s from table B which have a relation to a list of ID s of table A .

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 .

How could I do this with an SQL query ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM