基于多个表的多个表的Postgres / SQL计数

时间:2019-05-28 16:42:07

标签: sql postgresql

我有4个表,目标是根据给定的AccountLink来确定是否存在ResourceLinkUser.uuid的简单的是非题(如果更容易,则计数)和Resource.uuid

最小的工作示例

http://sqlfiddle.com/#!17/09144/1

目标

基于User.uuidResource.uuid的正确/错误响应,两者无关。

架构

User
- id
- uuid

Resource
- id
- account_id
- uuid

AccountLink
- id
- account_id
- user_id

ResourceLink
- id
- resource_id
- user_id

当前正在工作

给出id列表而不是true / false,可以在应用程序代码中进行处理,但查询本身效率也不高:

SELECT id
FROM "AccountLinks"
WHERE user_id = (SELECT id FROM "Users" WHERE uuid = ?) 
  AND account_id = (SELECT account_id FROM "Resources" WHERE uuid = ?)
UNION
SELECT id
FROM "ResourceLinks"
WHERE user_id = (SELECT id FROM "Users" WHERE uuid = ?)
  AND resource_id = (SELECT id FROM "Resources" WHERE uuid = ?)

是否有一种方法可以根据它们的user一次找到正确的resourceuuid,然后使用这些id属性来对多个表进行计数?

1 个答案:

答案 0 :(得分:1)

嗯。 。 。我认为您希望cross join带有其他信息:

select 
  (exists (select 1
     from "AccountLinks" al
     where al.user_id = u.id and al.account_id = r.account_id
  )) as has_accountlink,
  (exists (select 1
     from "ResourceLinks" rl
     where rl.user_id = u.id and rl.resource_id = r.id
  )) as has_resourcelink
from "Users" u cross join
     "Resources" r 
where u.uuid = ? and r.uuid = ?