繁体   English   中英

sql在多对多关系中得到交集

[英]sql to get intersection in a many to many relation

我有2个表CG ,以及包含2列c.id and g.id的多对多关联表CG 我要执行的查询是:

find the set of names in G that are common to a given set of names in C.

说, c1链接到g1g2c2链接到g2g3 ,我要求{c1, c2}的公共集,答案是{g2} {c1, c2}将带有WHERE ... IN子句。

是否有任何表述此查询的指针,而不使用PL / SQL?

您可以使用group byhaving来完成此操作。 这是一般结构:

select g.id
from cg
where c.id in (. . .)
group by g.id
having count(distinct case when c.id in (. . .) then c.id end) = # items in list

这是四个项目的示例:

select g.id
from cg
where c.id in (1, 3, 5, 7)
group by g.id
having count(distinct case when c.id in (1, 3, 5, 7) then c.id end) = 4 

暂无
暂无

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

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