【问题标题】:PostgreSQL: Friends of friends, but my relationship to those friendsPostgreSQL:朋友的朋友,但我与那些朋友的关系
【发布时间】:2017-03-07 15:37:55
【问题描述】:

我有两个表,usersconnections,它们有这些列:

CREATE TABLE users (
    id serial PRIMARY KEY,
    name text
);

CREATE TABLE connections (
    from_id int REFERENCES users (id) ON DELETE CASCADE,
    to_id int REFERENCES users (id) ON DELETE CASCADE,
    status connection_status,
    PRIMARY KEY (from_id, to_id),
    UNIQUE (from_id, to_id)
);

我也有这种类型:

CREATE TYPE connections_status AS ENUM ('accepted', 'pending');

connections 表将为每个连接包含一行,因此如果 user1 与 user2 有一个连接,它将是一行,但这并不意味着 user2 与 user1 有一个连接。像 Instagram 或 Twitter 一样查看它,在那里你有追随者并且你正在关注人们。因此,如果数据库中有一行 user1 为 from_id 且 user2 为 to_id 则表示 user1 正在关注 user2。

问题

我想在一个查询中获取用户连接以及我与他的连接的关系。例如,假设我是 user1,我想查找 user2 的所有连接(已接受和待处理的关注者和关注者)以及我与 user2 的连接的连接,可以是接受、待处理或 null。

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    查看附加的查询,我与用户加入了两次连接 1. users.id 和 connection.from_id,这个加入会带来 user1 关注的所有用户,状态如下 2. users.id 和connection.to_id,这个join 会将所有跟随user1 的用户都带上状态。

    非常无能为力:如果 user1 有多个连接,您将为每个组合恢复行。

    如果你想为每个用户获得一行,你可以使用 windows 函数,领先和滞后

    select user.id as user,
           user.name,
           following.from_id as user_following,
           following.status as status_following,
           followees.from_id as user_followees,
           followees.status as status_followees
    from users
    left join connections following on users.id=following .from_id
    left join connections followees on users.id=followees.from_id
    

    【讨论】:

      猜你喜欢
      • 2011-08-10
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 2013-08-15
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多