Q:

Batch count in Active Record or mysql

My goal is to export votes, per model object for a given collection. In this example I use .all, but in the wild, it will be a .where that yields the large set. I have the following query that I am concerned about:
Model.all.each{|x|puts x.votes.count}.explain

   (0.4ms)  SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 1
0
   (0.3ms)  SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 2
0
   (0.4ms)  SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 3
1
   (0.3ms)  SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 4
0
   (0.2ms)  SELECT COUNT(*) FROM `votes` WHERE `votes`.`entry_id` = 5
0

Individually count is very quick, but I don't feel comfortable calling All, especially when I have a collection in the thousands or millions. Is there a way to count records as a batch opporation?

A:

Not sure what you mean by "All", but do the same thing, only try using GROUP BY the ID and the COUNT function.  Something like this:
SELECT COUNT(*) FROM Votes GROUP BY entry_id

