【问题标题】:Sql query to get the most popular post in railssql查询获取rails中最受欢迎的帖子
【发布时间】:2015-01-11 11:45:31
【问题描述】:

所以我有这个 sql 查询,我用它来根据投票来获取最受欢迎的帖子,每个帖子都有一个指向它们的链接..

我想获取具有唯一链接的帖子,并且只获取得票最高的帖子。

ListsPost.find_by_sql("SELECT distinct lists_posts.*,
          COALESCE(rs_reputations.value, 0) AS votes FROM \"lists_posts\" LEFT JOIN rs_reputations ON
          lists_posts.id = rs_reputations.target_id AND rs_reputations.target_type = 'ListsPost' AND
          rs_reputations.reputation_name = 'votes' AND rs_reputations.active = 't'  ORDER BY votes desc, lists_posts.updated_at desc")

【问题讨论】:

    标签: mysql sql ruby-on-rails activerecord


    【解决方案1】:

    没有任何更详细的信息,我构建了这个查询,所以希望最好

    SELECT lists_posts.*, rs_reputations.value
      FROM \"lists_posts\" 
      LEFT JOIN rs_reputations 
        ON  lists_posts.id = rs_reputations.target_id 
       AND rs_reputations.target_type = 'ListsPost' 
       AND rs_reputations.reputation_name = 'votes' 
       AND rs_reputations.active = 't'  
       AND rs_reputations.value IN (     SELECT MAX(COALESCE(rs_reputations.value, 0)) AS max_votes 
                              FROM \"lists_posts\" 
                              LEFT JOIN rs_reputations 
                                ON  lists_posts.id = rs_reputations.target_id 
                               AND rs_reputations.target_type = 'ListsPost' 
                               AND rs_reputations.reputation_name = 'votes' 
                               AND rs_reputations.active = 't'  
                             )
    

    两步:

    1) 子选择找到一个最大值MAX(COALESCE(rs_reputations.value, 0)) 2)主选择搜索并显示具有此rs_reputations.value的所有记录

    有了表结构的详细信息,我的查询就可以优化了。

    【讨论】:

    • 这似乎可行。问题是,每个list_posts 里面都有一个帖子,我想找到具有相同帖子的lists_posts,但只返回投票最高的帖子
    【解决方案2】:

    经过多次反复试验,我决定从头开始,我想出了这个。它似乎工作,但可以做一点精炼。

    SELECT lp.*, COALESCE(rs_reputations.value, 0) as votes
    FROM lists_posts AS lp
    INNER JOIN(
      SELECT lists_posts.post_id, lists_posts.id, MAX(rs_reputations.value)
      FROM lists_posts
      LEFT JOIN rs_reputations
      ON lists_posts.id = rs_reputations.target_id
      GROUP BY lists_posts.post_id)l
    ON lp.post_id = l.post_id
    AND lp.id = l.id
    LEFT JOIN rs_reputations ON
      lp.id = rs_reputations.target_id
    AND rs_reputations.target_type = 'ListsPost'
    AND rs_reputations.reputation_name = 'votes'
    AND rs_reputations.active = 't'
    ORDER BY votes desc, updated_at desc
    

    【讨论】:

      猜你喜欢
      • 2012-05-08
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      相关资源
      最近更新 更多