PostgreSQL:朋友的朋友,但我与这些朋友的关系



我有两个表, users and connections ,它们具有以下列:

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');

连接表将包含每个连接的一行,因此,如果User1与user2有连接,则将是一行,但这并不意味着User2与user1具有连接。看到它像Instagram或Twitter,您有关注者,您正在关注人们。因此,如果数据库中有一个行,则用User1为 from_id 和user2 as to_id ,这意味着User1正在遵循user2。

问题

我想在一个查询中获得用户的联系,以及我与他的连接的关系。例如,假设我是User1,我想找到用户2的所有连接(接受和待处理的关注者和关注者)以及我与用户2的连接的连接是什么,可以接受,待处理或null。

请参阅附件查询,我与用户两次连接1. users.id with connection.from_id,此加入将带来用户1遵循以下状态的所有用户2.用户.ID带有连接。

非常无能:如果User1具有比一个连接更多的连接,则每种组合都会恢复行。

如果您想为每个用户获取一行,则可以使用Windows功能,Lag和Lag

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

最新更新