I know the title isn't so describing but it's really hard to find something generic to describe my situation. If someone wants to edit, feel free...
So, I have a postgres database, with a users
table. I would like to store the users followed by one user, and I really don't see how I could do this. I would like to do like SELECT followed_users FROM users WHERE username='username'
and this would return me every usernames, or id, or whatever of each followed users. But I don't see any clean way to do this.
Maybe an example would be more describing: user1
is following user2
and user3
.
How to store who user1
is following?
EDIT: I don't know how many users the user will follow.
Thank you for your help.
答案 0 :(得分:3)
扩展我上面的评论,因为它变得罗嗦了:
使用
等列创建一个名为user_follows
的新表
user_id1 | user_id2
或
follower_id | follows_id
然后你可以查询:
SELECT t1.username as follower_username, t3.username as following_usernae
FROM users t1
INNER JOIN user_follows t2 ON t1.user_id = t2.follower_id
INNER JOIN users t3 ON t2.following_id = t3.user_id
WHERE t1.user_id = <your user>
最后,将您的表视为&#34; Objects&#34;。然后,当您遇到类似&#34的问题时;如何添加跟随其他用户的用户&#34;您可以确定此关系是新对象还是现有对象的属性。由于用户可能跟随多个其他用户而不是关系不是&#34;用户&#34;的良好属性,因此它获得自己的表user_follows
。
由于user_follows
只是两个用户可能彼此之间的一种关系,因此将该对象的范围增加到relationships
并将关系类型存储为属性是有意义的。表:
user_id1 | user_id2 | relationship_type
其中relationships.relationship_type
可能包含follows, student of, sister
等值...
所以新查询会是这样的:
SELECT t1.username as follower_username, t3.username as following_username
FROM users t1
INNER JOIN relationships t2 ON t1.user_id = t2.user_id1
INNER JOIN users t3 ON t2.user_id2 = t3.user_id
WHERE t1.user_id = <your user> AND t2.relationship_type = 'Follows';
答案 1 :(得分:1)
我要添加另一个表,让我们将其称为following
以便参数,这样可以保存他们所关注的用户和用户对:
CREATE TABLE following (
user_id INT NOT NULL REFERENCES users(id),
following_id INT NOT NULL REFERENCES users(id),
PRIMARY KEY (user_id, following_id)
)
然后,您可以通过加入users
表(两次)来查询特定用户所关注的所有用户。例如,获取我(用户名“mureinik”)所关注的所有用户的姓名:
SELECT fu.username
FROM following f
JOIN users u ON f.user_id = u.id
JOIN users fu ON f.user_id = fu.id
WHERE u.username = 'mureinik'