postgreSQL - 如何对 Join 模型结果有条件

postgreSQL - How to have condition on Join model result

我一直在努力研究如何将我的业务需求转化为 SQL 查询。

案件本身并没有那么复杂。我有两个主要的 tables userlist 以及它们之间的多对多关系,通过 userList table,用户可以通过具有特定角色连接到列表,例如作为所有者或协作者。

该示例的相关属性:

user     -> id 
list     -> id | isPublic (BOOL)
userList -> id | userId | listId | role (OWNER|COLLABORATOR)

我有一个 API 端点,允许用户(请求者)检索另一个用户(目标)的所有列表。我有以下两种情况:

案例 1:请求者 = 目标

我可以控制:

`SELECT
  "list".*,
  "userList"."id" AS "userList.id",
  "userList"."listId" AS "userList.listId"
FROM
  "list" AS "list"
INNER JOIN 
  "userList" AS "userList"
  ON "list"."id" = "userList"."listId" AND "userList"."userId" = '${targetUserId}'`;

案例 2:请求者 =/= 目标

这是我遇到的问题,因为我有以下额外限制:

所以我想做类似的事情: 获取 target 连接到的所有列表(无论角色如何)并且列表是 public 或者 requester 也连接到该列表。

示例数据

user table

id
----------
john
anna

list table

id   | isPublic
------------------
1        false
2        true
3        false

userList table

id   |    userId    |  listId    |  role
-          john          1          OWNER
-          john          2          OWNER
-          john          3          OWNER
-          anna          1          COLLABORATOR

安娜请求查看约翰的所有列表

期望的结果:

[{
   id: 1,
   isPublic: false
}, {
   id: 2,
   isPublic: true
}]

任何帮助将不胜感激:)

非常感谢

这是你想要的吗?

select l.*
from list
inner join userlist ul on ul.listid = l.id
group by l.id
having 
    bool_or(ul.role = 'OWNER' and ul.userid = 'john')  -- owned by John
    and (l.ispublic or bool_or(ul.userid = 'anna')     -- public or allowed to Anna