繁体   English   中英

如何在“ order”条件下使用“ where”子句

[英]How to use “where” clause with “order” condition

我有一个模型Trade ,其中包含traded_atpriceamount列。

并且有一个default_order这样的。

scope :default_order, -> {
  order(traded_at: :desc, price: :asc, amount: :desc)
}

我想通过使用此订单子句来过滤trades

这是我的没有订单条款的代码。

scope :newer_than, ->(trade) {
  where(<<-SQL)
    traded_at > '#{trade.traded_at.to_s(:db)}' OR
    (traded_at = '#{trade.traded_at.to_s(:db)}' AND price < #{trade.price}) OR
    (traded_at = '#{trade.traded_at.to_s(:db)}' AND price = #{trade.price} AND amount > #{trade.amount})
  SQL
}

当我为order子句添加一个条件时,我需要在where子句中添加4个条件。 我认为效率不高。 是否可以对where子句使用order条件?

Postgres支持ROW的概念。

SELECT * FROM tbl WHERE (a, b, c) > (1, 2, 3)  -- not for you!

但是有一个障碍 :以相同的顺序对行中的每个字段进行比较。 您的案件具有混合排序顺序( ASC / DESC ),这是一个排头兵。 但是,如果price是数字数据类型(似乎是一个安全的下注)-定义了否定符 ,则有一种解决方法:

... WHERE (a, -b, c) > (1, -2, 3)  -- for you

所以:

where(<<-SQL)
    (traded_at, -price, amount)
  > ('#{trade.traded_at.to_s(:db)}', #{trade.price} * -1 , #{trade.amount})
  SQL

或通过trade.price轻松否定并下跌* -1

甚至可以通过多列表达式索引来支持!

注意:这些都不能与NULL值一起正常使用,因为NULL值永远不会在您的WHERE子句中限定。

有关:

暂无
暂无

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

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