【问题标题】:how to combine where and order for SQL query如何结合 SQL 查询的 where 和 order
【发布时间】:2016-03-22 18:26:20
【问题描述】:

我的项目和赠款通过匹配连接起来。赠款有到期日。我想按赠款到期日期对项目的匹配项进行排序。

这让我得到了基于到期日期的匹配项:

def self.expires_date_between(from, to)
  Match.where(:grant_id => Grant.where("expires_at  >= ? and expires_at <= ?", from, to))
end

这会根据特定日期范围显示匹配项。

def current_matches
  range = user.current_period_range
  matches.expires_date_between(range[0], range[1])
end

这非常适合根据特定时间段显示赠款,但赠款未按日期顺序显示 (expires_at)。似乎赠款是按其创建日期排序的。如何更改我的查询,以便按到期日期顺序列出赠款?

我试过了:

def self.expires_date_between(from, to)
  Match.where(:grant_id => Grant.where("expires_at  >= ? and expires_at <= ?", from, to).order('expires_at asc'))
end

这不会引发错误,但也不会更改授权的顺序。有什么想法吗?

【问题讨论】:

  • 不要忘记BETWEEN 运算符,您可以将其与where(expires_at: from .. to) 一起使用。
  • 感谢您的提示,这让我的代码更加简洁!

标签: mysql ruby postgresql ruby-on-rails-4


【解决方案1】:

假设您已经在模型中定义了关联,这应该可以工作(但尚未经过测试):

Match
  .joins(:grant)
  .merge(Grant.where("expires_at  >= ? and expires_at <= ?", from, to))
  .order('expires_at asc')

【讨论】:

  • 这非常有效。我还添加了@tadman 的建议,最后得到了Match.joins(:grant).merge(Grant.where("expires_at BETWEEN ? AND ?", from, to)).order('expires_at asc')
猜你喜欢
  • 2021-12-09
  • 2013-02-14
  • 2010-10-24
  • 2021-08-25
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多