首页 > 解决方案 > Postgres多对多关系:从相关表中查找所有与一组行相关的行

问题描述

考虑三个表,我们称它们为groups, subgroupsanother_groups以及subgroups_another_groups指定 和 之间的多对多关系的subgroupsanother_groupssubgroups并且groups是一对多的关系,subgroups外键也是如此group_id

怎么可能选择another_groups所有与subgroups一个group有关系的?

标签: sqlpostgresql

解决方案


我假设您说的是这样的设置:

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连接到 agroups的表,除了那些没有与 this 连接的子组的表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
                   )
         );

推荐阅读