0

I have 4 tables, and the goal is a simple true/false (or count if it's easier) for whether there exists either an AccountLink or a ResourceLink based on given User.uuid and Resource.uuid.

Minimal working example

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

Goal

True/false response based on User.uuid and Resource.uuid, which are unrelated.

Schema

User
- id
- uuid

Resource
- id
- account_id
- uuid

AccountLink
- id
- account_id
- user_id

ResourceLink
- id
- resource_id
- user_id

Currently working

Gives id list instead of true/false, which can be handled in application code, but the query itself is also inefficient:

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

Is there a way to find the correct user and resource once based on their uuid, and then use those id properties to count across multiple tables?

3
  • You mention count and true/false, but your query return a list of id. so not sure what result you want Commented May 28, 2019 at 16:53
  • Is user.uuid related to resource.uuid? or are two separated inputs? Commented May 28, 2019 at 16:56
  • @JuanCarlosOropeza updated my question to clarify Commented May 28, 2019 at 17:09

1 Answer 1

1

Hmmm . . . I think you want a cross join with additional information brought in:

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 = ?
Sign up to request clarification or add additional context in comments.

2 Comments

You miss the LEFT JOIN ON condition. Also resource.uuid seem to have an input variable too.
I'll look into cross join. Meanwhile uuid is different for User and for Resource. I have updated my question to reflect this more clearly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.