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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.