如何获得具有可见性条件的关注用户 post 提要?

How to get following users post feed that has visibility condition?

我正在尝试在 postgresql 数据库上进行 SQL 查询,该查询应该提供我的帖子的帖子提要以及我关注的用户和我的朋友(相互关注)的帖子我有这个 table结构

users table
id  username
1   me
2   user2
3   user3
4   user4
relationships table
id follower_id following_id
1   1           2 // me following user2
2   2           1 // user2 also following me so we are friends
3   3           1
posts table
id user_id post visibility
1   2      post1  friends
2   2      post2  public
3   2      post3  public
4   1      post4  public
5   3      post5  public
select p.*
from posts p
where (
    visibility = 'friends' and 
    user_id in (select following_id from relationships r1 where r1.follower_id = 1) and
    user_id in (select follower_id from relationships r2 where r2.following_id = 1)
) or (
    visibility = 'public' and 
    user_id in (select following_id from relationships r3 where follower_id = 1)
)

这是我进行的查询,它给出了一个结果,但对我来说这不是一个有效的查询我需要一个更好的查询来获得结果

用户 id 1 的提要应该是

id user_id post   visibility
1   2      post1  friends
2   2      post2  public
3   2      post3  public
4   1      post4  public

看下一个查询:

select p.*
from posts p
join (
    -- get followers and friends
    select distinct relationships.*, coalesce(friends.follower_id, 0) as friend_id
    from relationships
    -- join self for check is follower friend
    left join relationships friends on 
        relationships.following_id = friends.follower_id and
        relationships.follower_id = friends.following_id
    where relationships.follower_id = 1
) followers on (
    visibility = 'friends' and followers.friend_id = p.user_id or
    visibility = 'public' and followers.following_id = p.user_id 
);

SQLize.online

上尝试此查询