首页 > 解决方案 > 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

提前致谢!

标签: postgresqlarray-agg

解决方案


好的,我最终构建了正确的查询,如下所示:

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))
               )

推荐阅读