B-M*_*B-M 5 sql ruby-on-rails rails-activerecord
我正在尝试检索所有expired_at为零且expired_at大于当前时间的记录。
我试过这个:
PriceRule.where("expired_at > ? OR expired_at = ?", DateTime.now, nil)
Run Code Online (Sandbox Code Playgroud)
但这只会返回expired_at大于DateTime.now. 为什么nil被忽视?
您还可以在这里利用 Rails or,它将IS NULL代替= NULL. 我还建议使用Time.current它,它对时区有更好的支持。
PriceRule
.where(expired_at: Time.current..)
.or(PriceRule.where(expired_at: nil))
Run Code Online (Sandbox Code Playgroud)
您当前的查询检查是否expired_at等于 null (通过= NULL),这不会评估为 true。相反,您希望使用 来查询该列是否为空值IS NULL。
因此,查询可以调整为以下内容:
PriceRule.where("expired_at > ? OR expired_at IS NULL", DateTime.now)
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望保留原来的参数结构,您可以nil像以前一样传递:
PriceRule.where("expired_at > ? OR expired_at IS ?", DateTime.now, nil)
Run Code Online (Sandbox Code Playgroud)