Sql查询获取rails中最受欢迎的帖子

时间:2015-01-11 11:45:32

标签: mysql sql ruby-on-rails activerecord

所以我有这个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")

2 个答案:

答案 0 :(得分:0)

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

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

对所有记录进行主选择搜索和显示

有关表结构的详细信息,我的查询可以进行优化。

答案 1 :(得分:0)

经过大量的反复试验后,我决定从头开始,我想出了这个。它似乎有效,但可以做一点精炼。

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