如何设计一个高性能的朋友朋友数据库表

时间:2016-09-14 11:54:46

标签: sql database postgresql database-design relational-database

对于一些上下文我目前正在开发一个名为http://www.clubsofa.org的网站,其中的概念是人们可以在谷歌地图上做朋友的朋友搜索,目的是让他们与第二个联系旅行时的学位朋友。 目前设置的是PostgreSQL,其中有一个名为friends的表,它存储两个唯一的用户ID(其中友谊只存储一次,例如a,人b表明a是b的朋友,b是a的朋友)。当查询朋友的朋友时,我得到了当前用户的所有朋友,然后搜索他们所有的朋友,但这需要很长时间,而且运行的AWS ec2实例上的用户很少。 我试过的另一种方法是以两种方式存储好友关系,然后在第一列上建立索引,但是,这稍微慢一点。 我考虑设置它的方法之一是将一个人朋友作为JSON对象存储在他们的user_details条目中,然后懒得更新,但还没有去测试它。

有没有什么好方法可以设置它?

1 个答案:

答案 0 :(得分:1)

通过在表单上放置一个视图,您可以更轻松地查询将“友谊”存储在“一个方向”的表格中...

create view all_friendships
as
select friend_from,
       friend_to
from   friendships
union all
select friend_to,
       friend_from
from   friendships;

在(friend_from,friend_to)和(friend_to,friend_from)上使用唯一索引,这应该易于维护且易于查询。

所以结交朋友的朋友会是:

select distinct
       f2.friend_to
from   all_friendships f1 join
       all_friendships f2 on (f2.friend_from = f1.friend_to)
where  f1.friend_from = 12345 and
       f2.friend_to != 12345;