sql - Postgres多对多关系:从相关表中查找所有与一组行相关的行
问题描述
考虑三个表,我们称它们为groups
, subgroups
,another_groups
以及subgroups_another_groups
指定 和 之间的多对多关系的subgroups
表another_groups
。subgroups
并且groups
是一对多的关系,subgroups
外键也是如此group_id
。
怎么可能选择another_groups
所有与subgroups
一个group
有关系的?
解决方案
我假设您说的是这样的设置:
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
)
);
推荐阅读
- vb.net - 是否可以在实例化时确定类的类型或在不强制转换的情况下转换类型?
- android - 我无法在 android studio 中查看项目结构
- r - 如何计算R中的列的唯一值
- react-native - React native + expo + Notifications = 您必须在 `app.json` 中提供 `notification.vapidPublicKey` 才能在 Web 上使用推送通知
- ruby-on-rails - 在 rspec 中使用主应用程序的辅助方法的 Rails 引擎测试控制器
- html - 在我的导航栏中添加一个下拉菜单将那个孩子移到了右边
- javascript - 属性 'border:none' 在 Safari 浏览器中无法正常工作
- python - 将来自networkx dict的信息附加到numpy数组的问题
- javascript - 我如何从 ajax 中的 php weeb 页面返回响应并将其保存在我的变量中
- python - 使用 if 语句和追加的列表理解 - Phyton