[英]sql to get intersection in a many to many relation
我有2个表C
和G
,以及包含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
链接到g1
和g2
, c2
链接到g2
和g3
,我要求{c1, c2}
的公共集,答案是{g2}
。 {c1, c2}
将带有WHERE ... IN子句。
是否有任何表述此查询的指针,而不使用PL / SQL?
您可以使用group by
和having
来完成此操作。 这是一般结构:
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.