Postgres多对多关系:查找所有与相关表

时间:2018-05-02 08:48:28

标签: sql postgresql

考虑三个表,让他们称之为groupssubgroupsanother_groups和表subgroups_another_groups,指定{{{{{}之间的多对多关系1}}和subgroupsanother_groupssubgroups属于一对多关系,因此groups具有外键subgroups

如何选择group_id another_groups中的所有subgroupsgroup有关系?

1 个答案:

答案 0 :(得分:1)

我认为你说的是​​这样的设置:

CREATE TABLE groups (
   id integer PRIMARY KEY
);

CREATE TABLE subgroups (
   id integer PRIMARY KEY,
   group_id integer REFERENCES groups NOT NULL
);
CREATE INDEX ON subgroups(group_id);

CREATE TABLE another_groups (
   id integer PRIMARY KEY
);

CREATE TABLE subgroups_another_groups (
   subgroup_id integer REFERENCES subgroups NOT NULL,
   another_groups_id integer REFERENCES another_groups NOT NULL,
   PRIMARY KEY(subgroup_id, another_groups_id)
);
CREATE INDEX ON subgroups_another_groups(another_groups_id);

然后,您想知道通过其他两个表连接到another_groups的所有groups,除了那些存在与此another_groups没有连接的子组的表,对吗?

在SQL中,这将是:

SELECT DISTINCT g.id, a.id
FROM another_groups a
   JOIN subgroups_another_groups sag ON a.id = sag.another_groups_id
   JOIN subgroups s ON sag.subgroup_id = s.id
   JOIN groups g ON s.group_id = g.id
WHERE NOT EXISTS
         (SELECT 1 FROM subgroups s1
          WHERE s1.group_id = g.id
            AND NOT EXISTS
                   (SELECT 1 FROM subgroups_another_groups sag1
                    WHERE sag1.subgroup_id = s1.id
                      AND sag1.another_groups_id = a.id
                   )
         );