我不知道如何恰当地表达这个问题。如何编写order()以使我的产品按(discounted_price || price) DESC排序?| ID|价格|折扣价格|| --|--|--|| 1 | 1 |null|| 2 | 3 |null|| 3 | 4 | 2 |应该返回id 1,3,2你如何正确表达这个问题?
order()
(discounted_price || price) DESC
pobjuy321#
使用COALESCE:
Product.order( # COALESCE(discounted_price, price) DESC Product.arel_table.then { |p| p.coalesce(p[:discounted_price], p[:price]) }.desc )
字符串这个函数在RDBMS中是相当标准化的,它返回第一个非空参数。
1yjd4xko2#
你应该能够做类似于:order(discounted_price: :desc, price: :desc)
order(discounted_price: :desc, price: :desc)
2条答案
按热度按时间pobjuy321#
使用COALESCE:
字符串
这个函数在RDBMS中是相当标准化的,它返回第一个非空参数。
1yjd4xko2#
你应该能够做类似于:
order(discounted_price: :desc, price: :desc)