Ruby:分组并计算结果数

时间:2010-08-23 16:16:58

标签: ruby-on-rails

如何在不获取数据的情况下计算“组”查询返回的结果数?到目前为止,我只是得到了结果的哈希表。 rails3中是否可以优化此查询?

Vote.group("question_id, user_id").where("question_id = 3").count.count
 => 2

在这种情况下,我们正在计算此哈希表=> {1=>10, 15=>1}

查询是:

SELECT COUNT(*) AS count_all, question_id, user_id AS question_id_user_id
FROM `votes`
WHERE (question_id = 3)
GROUP BY question_id, user_id

1 个答案:

答案 0 :(得分:1)

您可以使用count_by_sql:

Vote.count_by_sql("select count(*) from ( select 1 from Votes group by question_id, user_id )")

或者,您可以使用Rails构建查询,然后运行它:

 query = Vote.group(:question_id, :user_id).to_sql
 count = Vote.count_by_sql("select count(*) from ( #{query} )")