简体   繁体   English

Active Record或mysql中的批次计数

[英]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. 在此示例中,我使用.all,但在野外,它将使用.where产生较大的集合。 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. 个人计数非常快,但是打电话给All会让我感到不舒服,尤其是当我拥有成千上万个收藏夹时。 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. 不知道“全部”是什么意思,但是要执行相同的操作,请仅尝试使用GROUP BY ID和COUNT函数。 Something like this: 像这样:

SELECT COUNT(*) FROM Votes GROUP BY entry_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM