我的目标是根据给定集合的每个模型对象导出投票。在这个例子中,我使用.all,但在野外,它将是一个产生大集合的.where。我有以下关注的问题:
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
单独计数非常快,但我觉得打电话给All感觉不舒服,尤其是当我有数千或数百万的收藏品时。有没有办法将记录统计为批量操作?
答案 0 :(得分:0)
不确定“全部”是什么意思,但做同样的事情,只尝试使用GROUP BY ID和COUNT函数。像这样:
SELECT COUNT(*) FROM Votes GROUP BY entry_id