【发布时间】:2020-10-22 11:03:14
【问题描述】:
我正在尝试在 postgresql 数据库上进行 SQL 查询,它应该为我提供我的帖子和我关注的用户和我的朋友的帖子的帖子提要(这是相互关注)我有这个表结构
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
【问题讨论】:
标签: mysql sql postgresql subquery