2011-01-28 75 views
1

在rails 2.3.8我试图订购一个查询,首先发布评论数最多,投票数最多的帖子。对2列总和的查询排序

我已经尽力了新的方法添加到Post模型为:

def interestingness 
    self.comments_count + self.votes_count 
end 

post_of_the_moment = find(:all, :conditions => ["submitted_at BETWEEN ? and ?", from, to], 
          :order  => :interestingness, 
          :limit  => 10 
          ) 

但是这个代码给了我一个未知列错误。

我也试过这个

post_of_the_moment = find(:all, :conditions => ["submitted_at BETWEEN ? and ?", from, to], 
          :order  => "SUM(comments_count+votes_count) DESC", 
          :limit  => 10 
          ) 

这不会给我的错误,但把为结果只有1个有0条评论0票行。

我在做什么错?在顺序SUM()的分组结果集:

感谢, 奥古斯托

回答

2

试试这个:

post_of_the_moment = find(:all, :select => '*, comments_count + votes_count AS total', :conditions => ["submitted_at BETWEEN ? and ?", from, to], :order => "total DESC", :limit => 10) 

我也想看看你是否可以优化它,只有你实际需要的字段被替换*以上。同时检查你的MySQL索引是否正确,因为你想避免一个全表扫描等总结计数。

+0

您的第一次尝试不起作用的原因是因为'趣味性'仅在数据库查询之后计算。数据库本身并不知道你的模型 - 它只知道你在表中定义的列。 – 2011-01-28 11:29:02

0

想通了,我是做了错误。

这工作:

post_of_the_moment = find(:all, :conditions => ["submitted_at BETWEEN ? and ?", from, to], 
         :order  => "(comments_count+votes_count) DESC", 
         :limit  => 10 
         ) 

仍然不知道为什么我不能排序字段使用我创建的兴趣方法。

+1

趣味性是Ruby方法,但查找数据库查询。数据库不知道Ruby世界中的任何内容。 – Zr40 2011-03-06 11:17:22