I am breaking my brain on a SQL, maybe someone can give me a hint.
Example setup:
CREATE TABLE album
(
name text NOT NULL,
id serial NOT NULL,
user_id bigint NOT NULL
);
CREATE TABLE album_share
(
id integer NOT NULL,
user_id bigint NOT NULL,
album_id bigint NOT NULL,
permission character varying(20)
);
INSERT INTO album_share VALUES (21, 23, 8, 'OWNER');
--INSERT INTO album_share VALUES (22, 22, 8, 'READ');
INSERT INTO album VALUES ('album1', 8, 23);
INSERT INTO album VALUES ('album2', 12, 23);
INSERT INTO album VALUES ('album3', 13, 22);
INSERT INTO album VALUES ('album4', 15, 22);
--Expecting with user_id=23
-- album1,album2
--!! Failed: album1 is not in the result !!
SELECT * from album a
LEFT JOIN album_share share ON share.album_id = a.id
where (a.user_id = 23 or share.user_id = 23)
and (share.permission is null or share.permission != 'OWNER');
--Expecting with user_id=22
-- album3,album4
-- Works fine
SELECT * from album a
LEFT JOIN album_share share ON share.album_id = a.id
where (a.user_id = 22 or share.user_id = 22)
and (share.permission is null or share.permission != 'OWNER');
The example is also available online: http://rextester.com/DCD25332
I am trying to select from two tables joined and filterd by their data. It is better explained in the fiddle. The first query with user_id=23 doesn't select the album, I think its because of the filtering, but I can not solve it.



share.permission is null or share.permission != 'OWNER'. Since album_id = 8 permission is set toOWNER, your SQL criteria will always be FALSE. - Maruli