繁体   English   中英

如何在函数而不是数据库列上运行where子句?

[英]How to run where clause on a function rather than a database column?

在我的Invoice模型中,我试图获取所有未结发票:

class Invoice < ActiveRecord::Base

  has_many :payments

  def self.outstanding
    where("outstanding_amount != 0")
  end

  private

  def outstanding_amount
    total - payments.to_a.sum(&:amount_in_cents)
  end

end

但是,这不起作用,因为我没有数据库列outstanding_amount 有什么方法可以在函数而不是数据库字段上运行where子句吗?

谢谢你的帮助。

您需要将表达式作为having子句的一部分传递。 我将遵循RoR向导中的活动记录语法,但是您的最终查询应为:

select ...
from ... join payments on ...
where ...
group by ...
having total != sum(payments.amount)

如果大多数行不平衡(不太可能),则可以使用相关子查询作为替代:

select ...
from ...
where ...
and total != (select sum(amount) from payment where ...)

(如果大多数行不平衡,请不要执行上述操作,因为这样会降低性能。)

最后一种选择(我实际上建议这样做)是维护一个paid列-理想情况下,尽管不一定要使用触发器。 然后,您可以使用:

select ...
from ...
where ...
and total != paid

更好的是,您可以将后者改写为:

where total - paid != 0

然后在(total - paid) where (total - paid != 0)上添加部分索引,以实现最佳性能。

暂无
暂无

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

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