2017-03-07 138 views
0

我有两个表,用户连接,他们有这些列关系:PostgreSQL的:朋友的朋友,但我的那些朋友们

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为to_id这意味着user1跟随user2。

问题

我想获得一个用户的连接,并在一个查询我到他的连接关系。例如,假设我是user1,我想查找user2的所有连接(接受和未决的追随者和followees),以及我的连接与user2的连接(可以接受,挂起或空)。

回答

0

见附件查询,我加入了连接两次与用户 1 users.id与connection.from_id,这个连接会带来所有的user1的状态如下 2. users.id与connection.to_id以下的用户,这个连接将使所有跟在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