Twitter主页/ Facebook墙的数据库结构?

时间:2010-03-28 21:33:32

标签: mysql feed facebook-wall

基本上是所有朋友最近帖子的实时提要。

在一种愚蠢的方法中,我认为我首先要构建一个类似的查询:

SELECT * FROM tblposts WHERE userid= friend_id_1 OR userid= friend_id_2 ......依此类推

其中friend_id_%是朋友列表中朋友的用户ID。但这必须是一种非常低效的方式,对吧?在MySQL中有没有更快的方法呢?也许是一些聪明的数据库架构?

(我知道FB使用Hadoob,但我没有足够的经验去那么远:()

2 个答案:

答案 0 :(得分:2)

如果您有要查询的ID列表,则应使用IN:

SELECT * FROM tblposts WHERE userid IN (friend_id_1, friend_id_2, ...)

但在这种情况下,我认为你可以使用连接。

SELECT * FROM tblposts AS T1
JOIN (
   SELECT friendid             -- I just made up this query.
   FROM friends                -- You need to replace it with the
   WHERE userid = 'youruserid' -- real query to get someone's friends.
) AS T2
ON T1.userid = T2.friendid

答案 1 :(得分:0)

很抱歉,但我认为上面的查询意味着friends表有很多冗余记录? (x是y的朋友,y是x的朋友; 2个记录?)

如果friends表格包含字段sender_id receiver_idrequest_status,则可以修改上述查询,使其返回针对youruserid的好友列表,即如果sender_id == youruserid选择receiver_id的值,反之亦然,那么我们得到一个youruserid所有朋友的列表?我想不出更好的表来避免重复。