开发者

Ruby: group and count the number of results

How can I count the number of results returned by a "group" 开发者_如何学编程query without getting the data ? So far, I am just getting a hashtable of results. Is it possible in rails3 to optimize this query ?

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

In this case we are doing a count of this hashtable => {1=>10, 15=>1}

Query is:

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


You can use count_by_sql:

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

Or, you can build up the query using Rails, and then run it:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜