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

时间:2015-02-06 01:31:05

标签: sql oracle set many-to-many intersection

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

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

说,c1g1g2相关联,c2g2g3相关联,我要求{c1, c2}的公共集合,答案是{g2}{c1, c2}将提供WHERE ... IN子句。

有关制定此查询的指针,而不是使用PL / SQL吗?

1 个答案:

答案 0 :(得分:0)

您可以使用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