请查看下面的答案,让我知道它是否返回您想要的输出:
模式和插入语句:
create table users_collections (user_id int, collection_id int, access varchar(20));
insert into users_collections values(3, 1, 'allow');
insert into users_collections values(3, 2, 'allow');
insert into users_collections values(4, 3, 'allow');
insert into users_collections values(3, 5, 'not allow');
create table collections_books (collection_id int, book_id int);
insert into collections_books values(2,24);
insert into collections_books values(3,35);
insert into collections_books values(3,25);
insert into collections_books values(1,36);
insert into collections_books values(1,22);
insert into collections_books values(1,24);
insert into collections_books values(2,34);
insert into collections_books values(5,344);
insert into collections_books values(6,474);
询问:
SELECT c.collection_id, (CASE WHEN max(u.access) = 'allow' AND max(u.user_id) = 3
THEN ARRAY_AGG(c.book_id)
ELSE '{null}'::int[] END)
FROM collections_books AS c
LEFT JOIN users_collections AS u
ON c.collection_id = u.collection_id
GROUP BY c.collection_id;
输出:
|collection_id | case |
|------------: | :---------|
| 3 | {35,25} |
| 5 | {NULL} |
| 6 | {NULL} |
| 2 | {24,34} |
| 1 | {36,24,22}|
db<小提琴在这里