I’ve got a many-to-many accounts <-> users relationship. I’m trying to pull all the accounts shared by me and another user. So far I have something I modified from this answer:
SELECT *
FROM user
JOIN account_user ON account_user.user_id = user.id
JOIN account ON account.id = account_user.account_id
WHERE user.id IN ({my_id},{other_user_id})
GROUP BY account.id
HAVING COUNT(DISTINCT user.id) = 2
This seems to be on the right track, but the account_user table has a ‘role’ field, and I want to make sure that the record I get back contains the role of the other user, not mine. How would I tweak this to make that happen?
This works under my Oracle and the same basic idea should work under any DBMS:
In plain English:
accountandaccount_userfor the other user.You can easily join
useron top of that if you need to (as indicated by your SQL, but not by your question).