postgresql - Postgres 复杂查询以获取具有与具有特定值的另一个表连接的对应列的列值
问题描述
我有两个 Postgres 表:
1- relationships:
| user_id | target_user_id |
2- affiliations:
| user_id | user_type_id | current |
来自 affiliations 的 user_id 可以是关系中的两个列值中的任何一个,并且 current in affiliations 是一个布尔值。
在关系中,user_id 不是唯一的,可以有多个对应的 target_user_id 值。
我想从附属关系中获取一个 user_id 列表,这些列表也在关系中的 user_id 列中,并且它们所有相应的 target_user_id 值都将它们在附属关系中的“当前”值设置为 false
例子:
relationships:
user_id | target_user_id
1 | 11
1 | 12
1 | 13
2 | 14
2 | 15
2 | 16
affiliations:
user_id | current
1 | true
11 | false
12 | false
13 | false
2 | false
14 | true
15 | false
15 | false
所以我希望查询只返回 1,因为用户 2 没有其所有对应的 target_user_id 其当前为 false
提前致谢!
解决方案
好的,我最终构建了正确的查询,如下所示:
UPDATE app.affiliations
SET current = true
where current = false
and user_id in (select r.user_id
from app.affiliations as a join app.relationships as r
on r.target_user_id = a.user_id
group by r.user_id
having false = ALL(array_agg(a.current))
)
推荐阅读
- python - 如何在 python 3 上生成正弦波音调
- excel - 适用于 Microsoft Office (AMO) 的 Excel 加载项 - 使用 VBA 删除存储过程对象和保留值
- java - 使用 Streams 展平 Java 对象
- linux - 在 Yocto 中使用串行控制台登录时启用 root 密码验证
- java - 基本的 MVC 结构问题
- javascript - 响应式导航栏 - 单击时移动的下拉符号
- html - 如何阻止音频元素重叠导航
- visual-studio-code - 防止 VS Code 在另存为时将光标移动到文件开头
- reporting-services - 使用 IIF() 函数的 SSRS 报表生成器表达式无法正确评估包含“<”和“>”字符的条件
- python - VTK 检查多数据点对象的交叉点