【问题标题】:GROUP BY and COUNT using ActiveRecord使用 ActiveRecord 进行 GROUP BY 和 COUNT
【发布时间】:2015-10-30 23:34:33
【问题描述】:

参考这个: Is there any difference between GROUP BY and DISTINCT

Given a table that looks like this:

name
------
barry
dave
bill
dave
dave
barry
john
This query:

SELECT name, count(*) AS count FROM table GROUP BY name;
Will produce output like this:

name    count
-------------
barry   2
dave    3
bill    1
john    1

对于 ActiveModel 使用 COUNT 执行 GROUP BY 的正确 Rails 约定是什么?

【问题讨论】:

  • Table.all.group(:name).count

标签: sql ruby-on-rails ruby postgresql activerecord


【解决方案1】:

DistinctGroup By 会给你不同的结果。要获得您希望使用的结果

Person.group(:name).count
(1.2ms)  SELECT COUNT(*) AS count_all, name AS name FROM "people" GROUP BY "people"."name"
=> {"Dan"=>3, "Dave"=>2, "Vic"=>1} 

如上所示,group 会将事物作为哈希返回。虽然 distinct 只返回总人数,如下所示。

Person.distinct(:name).count
(0.4ms)  SELECT DISTINCT COUNT(DISTINCT "people"."id") FROM "people"
=> 6 

【讨论】:

  • 这是哪个 Rails 版本?
  • 4.2+ 根据我的经验
  • 4.2+ 不需要all,只需Person.group(:name).count
  • 对于希望重现上述不同计数查询的任何人,Person.distinct(:name).count 现在将返回与Person.count 相同的值。这显然不是想要的结果。这些天来,您需要执行Person.distinct.count(:name),才能获得6
【解决方案2】:

请注意,接受的答案将返回一个哈希:

Tagging.joins(:tag).group(:name).size
   (0.4ms)  SELECT COUNT(*) AS count_all, `name` AS name FROM `taggings` INNER JOIN `tags` ON `tags`.`id` = `taggings`.`tag_id` GROUP BY `name`
 => {"applesauce"=>1, "oranges"=>2} 

但是,如果您想在连接中返回计数以及来自不同表的一些列,该怎么办。然后你还需要使用 select ActiveRecord 查询:

collection = Tagging.select('COUNT(*) as total, taggings.taggable_id, taggings.taggable_type').joins(:tag).where(taggable_type: 'LineItem', taggable_id: ['5cad0dcc3ed1496086000031', '5cad0dcd3ed1496086000081'] ).group(:name)

collection.each do |item|
  puts item.taggable_id
  puts item.total
end

5cad0dcc3ed1496086000031
1
5cad0dcc3ed1496086000031
2

使用第二种方法,您可以获取有关连接关系的更多详细信息,而无需任何额外的查询或循环构造。

【讨论】:

    【解决方案3】:

    另一种选择:

    Person.select(:name, 'COUNT(name)').group(:name)
    

    这会生成一个具有属性计数的人员数组

    【讨论】:

      【解决方案4】:

      另一种选择:

      Person.select(:name).distinct(:name).count
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2017-02-24
      • 2021-10-02
      • 2016-10-11
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 2023-03-18
      相关资源
      最近更新 更多