Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 一个连接有多少个计数?_Ruby On Rails - Fatal编程技术网

Ruby on rails 一个连接有多少个计数?

Ruby on rails 一个连接有多少个计数?,ruby-on-rails,Ruby On Rails,我想进行以下查询: SELECT COUNT(DISTINCT a.id) as countaid, sum(b.id) as countbid FROM a INNER JOIN b ON a.id = b.id WHERE b.otherfield = 0; 有一个指望: Aclass.joins(:b).where( bclass: {"otherfield" = 0} ).count(:id) 如何进行计数计数(不同:id)计数(:id,distinct=>true)? 谢谢大家!

我想进行以下查询:

SELECT COUNT(DISTINCT a.id) as countaid, sum(b.id) as countbid FROM a
INNER JOIN b ON a.id = b.id
WHERE b.otherfield = 0;
有一个指望:

Aclass.joins(:b).where( bclass: {"otherfield" = 0} ).count(:id)
如何进行计数<代码>计数(不同:id)<代码>计数(:id,distinct=>true)? 谢谢大家!

您可以在rails 3:

Aclass.select("DISTINCT a.id").joins(:b).where( bclass: {otherfield: 0} ).count
在rails 4中:

Aclass.distinct.joins(:b).where( bclass: {otherfield: 0} ).count(:id)

我想用符号。像
select([count(distinct(Aclass.table\u name.:id)、sum(Bclass.table\u name.:id)])
不要这样做。性能会很糟糕。
collect(&:id)
将返回一个id数组,该数组将以Ruby(而不是SQL)进行计数。这种类型的任务应该由数据库处理。