我有表A和B的关系:A< - > 1 B关系。
它们通过字段A.b = B.id连接,其中B.id是唯一的
我有一个参数,它是B的一堆ID。
我希望获得明确的A.id,其中所有已分配B.ids。
实施例
表B
| id | ...
| 1 |
| 2 |
| 3 |
表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 |
参数B.ids =&#34; 1,2,3&#34; 的预期结果:1,3(2错过所需的B.id = 3)
我该怎么做?
答案 0 :(得分:4)
您可以使用聚合和having
子句执行此操作:
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);
请注意,这可以通过一些假设来简化。例如,如果您知道b
ID是唯一的,那么您不需要count(distinct)
(count()
就足够了。)
编辑:
如果您想要查看要查看的ID列表,可以使用:
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);
答案 1 :(得分: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);