我应该如何构建数据库/构建查询,在其中按朋友“互动”数量对帖子进行排序?与它

发布于 2025-01-01 05:47:51 字数 355 浏览 0 评论 0原文

我想在 Rails 3.2 (MYSQL) 中构建一个查询,其中我根据与其交互的朋友数量对一组帖子进行排序。我可以将其限制为最后 7 天。我当前的想法是:

  1. 维护以下表格/关系: 用户有很多朋友 Post 有很多 Interactors

  2. __ :) 我不太确定如何最有效地构建查询。也许,我天真地认为我应该首先查询以获取用户朋友.. 将其放入数组中.. 然后查询交互者(过去 7 天),其中 user_id 位于我的朋友列表中.. 在此查询中,也延迟加载帖子..然后在前端计算每个帖子的交互者数量..将其附加到帖子..然后对它们进行排序?一定是一种更有效的方法..

谢谢!

I want to build a query in Rails 3.2 (MYSQL), where I sort a group of posts by the number of your friends that are interacting with it. I can limit this to last 7 days.. My current thinking is:

  1. Maintain the following tables / relationships:
    Users has many Friends
    Post has many Interactors

  2. __ :) I'm not quite sure how to most efficiently build the query. Perhaps, naively Id' think I'd first query to get the users friends.. put that into an array.. then query the interactors (last 7 days), where the user_id is 'in' my friends list.. in this query, lazy load the posts as well.. then on the front end count the number of interactors per post.. attach that to the posts.. and then sort them? Must be a more efficient way..

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挖鼻大婶 2025-01-08 05:47:51

假设有一个包含 UserIDFriendIDFriend 表,以及包含 PostID< 的 PostInteraction 表。 /code> 和 UserID,你会:

select pi.PostID, count(distinct f.FriendID) as Count
from PostInteraction pi
inner join Friend f on pi.UserID = f.FriendID
where f.UserID = @MyUserID
group by pi.PostID
order by count(distinct f.FriendID) desc

我假设同一个朋友可以与一个帖子进行多次交互,而你只想计算一次,因此使用 DISTINCT 在计数中。

Assuming there is a Friend table containing UserID and FriendID, and a PostInteraction table that contains PostID and UserID, you would:

select pi.PostID, count(distinct f.FriendID) as Count
from PostInteraction pi
inner join Friend f on pi.UserID = f.FriendID
where f.UserID = @MyUserID
group by pi.PostID
order by count(distinct f.FriendID) desc

I have assumed the same friend could have multiple interactions with a post and that you only want to count that once, thus the use of DISTINCT in the count.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文