获取每个组的最新n条记录

时间:2014-11-23 17:00:41

标签: ruby-on-rails ruby activerecord

我有两个型号: 话题 评论

主题has_many评论

我如何才能获得每个主题的最后4条评论?

我试过这个但是很慢:

Comment.
      joins("INNER JOIN (SELECT m1.id,m1.topic_id, COUNT(m2.id) as c FROM multimedias as m1 LEFT JOin multimedias as m2 ON 
        m1.topic_id = m2.topic_id  AND m1.id < m2.id 
        WHERE m1.topic_id IS NOT NULL GROUP BY m1.id, m1.topic_id HAVING c < 4
        ORDER by m1.topic_id, c desc) as m3 ON m3.id = multimedias.id").
      where([ "multimedias.topic_id IN (?)", topics_id ]) 

3 个答案:

答案 0 :(得分:0)

您可以尝试使用last方法

答案 1 :(得分:0)

#last方法将整数作为参数,因此您只需使用Comment.last(4)

答案 2 :(得分:0)

的ActiveRecord :: FinderMethods#尾

#last有一个可选参数,允许您指定最后N条记录,如下所示:

Comment.
      joins("INNER JOIN (SELECT m1.id,m1.topic_id, COUNT(m2.id) as c FROM multimedias as m1 LEFT JOin multimedias as m2 ON 
        m1.topic_id = m2.topic_id  AND m1.id < m2.id 
        WHERE m1.topic_id IS NOT NULL GROUP BY m1.id, m1.topic_id HAVING c < 4
        ORDER by m1.topic_id, c desc) as m3 ON m3.id = multimedias.id").
      where([ "multimedias.topic_id IN (?)", topics_id ]).
      last(4)