合并和排序同一模型中的两列 [英] merge and order two columns in the same model

查看:59
本文介绍了合并和排序同一模型中的两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个ActiveRecord模型Foo,它有两个日期列date_1和date_2,并且我想按两列中的较晚者(较晚的日期)进行排序,该怎么做?答案将根据代码的简单性和使用最少的sql进行判断。



类似问题
Ruby或Rails对两个/多个日期字段进行排序



<我倾向于以下内容,但我不知道是否有更好的方法。
经过测试的代码:

  Foo.select( CASE 
,当date_1> date_2 THEN date_1
ELSE date_2
END AS Later_date,*)。order( later_date desc)


解决方案

尝试使用以下方法:

  Foo.order('GREATEST(date_1,date_2 )DESC')


If I had an ActiveRecord model, Foo, which had two date columns, date_1 and date_2, and I wanted to sort by the later of the two columns (the date that was later), how would this be done? Answers will be judged based on simplicity of the code and the least sql used.

similar question Ruby or Rails sort on two/multiple date fields

I'm leaning towards the following but I don't know if there is a better way. Tested code:

 Foo.select("CASE 
     WHEN date_1 > date_2 THEN date_1
     ELSE date_2
     END AS later_date, *").order("later_date desc")

解决方案

Try using this:

Foo.order('GREATEST(date_1, date_2) DESC')

这篇关于合并和排序同一模型中的两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆