考虑三个表,让他们称之为groups
,subgroups
,another_groups
和表subgroups_another_groups
,指定{{{{{}之间的多对多关系1}}和subgroups
。 another_groups
和subgroups
属于一对多关系,因此groups
具有外键subgroups
。
如何选择group_id
another_groups
中的所有subgroups
与group
有关系?
答案 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
)
);