GROUP BY和COUNT使用ActiveRecord

问题描述 投票:23回答:2

参考这个:qazxsw poi

Is there any difference between GROUP BY and DISTINCT

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

sql ruby-on-rails ruby postgresql activerecord
2个回答
49
投票

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 Distinct会给你不同的结果。要获得您希望使用的结果

Group By

如上所述,group将返回哈希值。虽然不同只是返回总人数,见下文。

Person.all.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} 

1
投票

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

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

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

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} 

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

© www.soinside.com 2019 - 2024. All rights reserved.