I have 2 tables:
collections_books (collection_id, book_id)
users_collections (user_id, collection_id, access)
I'm using PostgreSQL
.
The following query gives me a list of book_id
s grouped by collection_id
s. The problem is, since I'm using where condition, the results are limited to only the collections allowed for user_id = 3.
But, I want all the collection_id
s and the corresponding book_id
s
- As an array, if the user_id has
access = allow
- As an empty array, if the
user_id
is not present in theusers_collections
oruser_id != allow
SELECT c.collection_id, ARRAY_AGG(c.book_id)
FROM collections_books AS c
LEFT JOIN users_collections AS u
ON c.collection_id = u.collection_id
WHERE
u.access = 'allow' AND
u.user_id = 3
GROUP BY c.collection_id;