背景:
我尝试过的事情:
直接为喜欢的用户返回喜欢的帖子很容易,我会逐页跟踪 顶部的用户 :
SELECT uid, date,
EXISTS(SELECT 1 FROM Follows a WHERE a.uid = "1" and a.followsUid = Likes.uid limit 1) as youFollow
FROM Likes WHERE pid = 30
ORDER BY youFollow DESC, date DESC LIMIT 10
此方法的问题在于,它仍然不会在列表顶部显示喜欢的帖子的所有所有用户-仅关注给定页面的用户(限制10)。
有没有办法在不扫描帖子的每个“赞”行的情况下实现这一目标?
我能想到的唯一另一种方法是“扇出” /收件箱模型,用户可以订阅喜欢的人。然后,我可以查询类似select * from LikeEvents where uid IN (people I follow) and postId = pid
的内容,但这似乎会导致大量冗余数据
答案 0 :(得分:0)
最简单的方法之一是加入Likes表和Follows表并按结果集进行排序。例如:
SELECT Likes.uid, Likes.date FROM Likes
LEFT JOIN Follows ON Follows.uid = 1 AND Follows.followsUid = Likes.uid
WHERE Likes.pid = 30
ORDER BY Follows.uid DESC, Likes.date DESC LIMIT 10
当然,如果要避免全表扫描,则必须在Likes表和Follows表上创建索引。例如:
CREATE INDEX likes_pid on Likes(pid);
CREATE INDEX follows_uid on Follows(uid);
另一种方法是在Likes表中创建一个等级列,并对其排序结果集。
SELECT * FROM Likes WHERE Likes.pid = 30 ORDER BY rank DESC, date DESC LIMIT 10
自然,您必须在创建“赞”时计算并更新等级列