简体   繁体   中英

SQL select distinct where exist row for each id in other table

I have table A and B with a relationship: A n<->1 B relationship.

They are joined over field Ab = B.id, where B.id is unique

I have a parameter which is a bunch of ids of B.

I want to get distinct A.id that have all given B.ids assigned.

Example:

Table B

| id | ...
| 1  |
| 2  |
| 3  |

Table A

| id |  b  | ...
| 1  |  1  |
| 1  |  2  |
| 1  |  3  |
| 2  |  1  |
| 2  |  2  |
               <-- id=2 is not assigned to b=3 !
| 3  |  1  |
| 3  |  2  |
| 3  |  3  |

Expected result for parameter B.ids="1,2,3" : 1, 3 (2 misses the required B.id=3)

How can I do this?

You can do this with aggregation and a having clause:

select id
from tableA a join
     tableB b
     on a.b = b.id
group by id
having count(distinct b) = (select count(distinct b) from tableB);

Note that this can possibly be simplified with some assumptions. For instance, if you know the b ids are unique, then you don't need the count(distinct) ( count() is then sufficient.)

EDIT:

If you want a list of ids that you want to check, you can use:

select id
from tableA a
where find_in_set(a.b, IDLISTHERE) > 0
group by id
having count(distinct b) = (select count(distinct b) from tableB where find_in_set(a.b, IDLISTHERE) > 0);
select id  from tableA a join tableB b  on a.b = b.id
group by id
having count(distinct b) = (select count(distinct b) from tableB);

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