繁体   English   中英

SQL为其他表中的每个ID选择不同的位置

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

我的表A和B具有以下关系:A n <-> 1 B关系。

它们通过字段Ab = B.id连接,其中B.id是唯一的

我有一个参数,它是一堆B的ID。

我想获得分配了所有给定B.id的独特A.id。

例:

表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 =“ 1,2,3”的预期结果 :1、3(2缺少必需的B.id = 3)

我怎样才能做到这一点?

您可以使用聚合和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);
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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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