我有4个表,目标是根据给定的AccountLink
来确定是否存在ResourceLink
或User.uuid
的简单的是非题(如果更容易,则计数)和Resource.uuid
。
http://sqlfiddle.com/#!17/09144/1
基于User.uuid
和Resource.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
一次找到正确的resource
和uuid
,然后使用这些id
属性来对多个表进行计数?
答案 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 = ?