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

旧街凉风 提交于 2019-12-01 13:49:16

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

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