Rails + PostgreSQL:如果一列中的值为 NULL,则按另一列中的值搜索
Rails + PostgreSQL: if value in one column is NULL, search by a value in a different column
在我的模型中,我有这些列:
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
(因为它现在在显示的范围内)。
我该如何实现?
提前致谢
可以使用 PostgreSQL 的原生 COALESCE()
函数吗?这正是您想要的:
.where("COALESCE(customer_invoiced_at, my_other_column) >= ?", date_from.to_datetime.beginning_of_day)
在我的模型中,我有这些列:
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
(因为它现在在显示的范围内)。
我该如何实现?
提前致谢
可以使用 PostgreSQL 的原生 COALESCE()
函数吗?这正是您想要的:
.where("COALESCE(customer_invoiced_at, my_other_column) >= ?", date_from.to_datetime.beginning_of_day)