Postgres 复杂查询以获取具有相应列的列值与另一个具有特定值的 table

Postgres Complex Query to get column values having corresponding column joined with another table having a specific value

我有两个 Postgres 表:

1- relationships:

    | user_id | target_user_id |

2- affiliations:

    | user_id | user_type_id | current |

user_id from affiliations 可以是 relationships 中两个列值中的任何一个,current in affiliations 是一个布尔值。

在关系中,user_id不是唯一的,可以有多个对应的target_user_id值。

我想从隶属关系中得到一个 user_id 的列表,它们也在关系的 user_id 列中,并且它们所有对应的 target_user_id 值都有它们的 'current' 从属关系中的值设置为 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

所以我只想查询 return 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))
               )