Reputation: 1537
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
Upvotes: 0
Views: 574
Reputation: 10773
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} )")
Upvotes: 2