【问题标题】:Rails + PostgreSQL: if value in one column is NULL, search by a value in a different columnRails + PostgreSQL:如果一列中的值为NULL,则按另一列中的值搜索
【发布时间】:2021-05-16 00:17:07
【问题描述】:

在我的模型中,我有这些列:

customer_invoiced_at: datetime
customer_invoice_at_custom: datetime

我正在尝试搜索给定日期与customer_invoiced_at 匹配的所有记录:

scope :by_customer_invoiced_at_from, (lambda do |date_from|
    self.where("customer_invoiced_at >= ?", date_from.to_datetime.beginning_of_day) if date_from.present?
end)

我需要稍微调整一下 - 如果 customer_invoice_at_custom 存在(不为 null 或空),我需要使用此字段而不是 customer_invoiced_at。但是,如果 customer_invoice_at_custom 为 NULL 或空,我想使用 customer_invoiced_at(因为它现在在显示的范围内)。

我如何做到这一点?

提前谢谢你

【问题讨论】:

    标签: ruby-on-rails ruby postgresql activerecord


    【解决方案1】:

    你可以使用PostgreSQL原生的COALESCE()函数吗?这正是您想要的:

    .where("COALESCE(customer_invoiced_at, my_other_column) >= ?", date_from.to_datetime.beginning_of_day)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多