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)进行计数。这种类型的任务应该由数据库处理。