【问题标题】:How to get following users post feed that has visibility condition?如何让关注用户发布具有可见性条件的提要?
【发布时间】: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


    【解决方案1】:

    查看下一个查询:

    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上试试这个查询

    【讨论】:

    • 我想我应该提到我正在使用 postgresql,它没有 ifnull 函数,当我们将此查询与我的比较时,您认为哪个更有效?
    • 好的。通过将 IFNULL 更改为 COALESCE 进行修复。在这里试试sqlize.online/…
    • 但我认为查询有问题,即使我将用户更改为 3,即使用户 3 没有关注用户 2,它仍然给我相同的结果
    • 哦不,你是对的,它给出了正确的列表我在其他查询中更改了用户我的错误。但是你认为这个查询的效率如何?我们有子查询和连接
    • 我很确定加入比 3 个子查询更有效。但最好的了解方法是在真实数据上运行。因此,如果您有足够大的数据集,只需运行并比较查询性能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2011-03-31
    • 2018-10-14
    • 2012-06-04
    • 1970-01-01
    相关资源
    最近更新 更多