Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何结合where和order进行SQL查询_Mysql_Ruby_Postgresql_Ruby On Rails 4 - Fatal编程技术网

Mysql 如何结合where和order进行SQL查询

Mysql 如何结合where和order进行SQL查询,mysql,ruby,postgresql,ruby-on-rails-4,Mysql,Ruby,Postgresql,Ruby On Rails 4,我的项目和补助金是通过匹配连接起来的。补助金有到期日。我想按授权到期日期对项目的匹配项进行排序 这是根据到期日期为我提供匹配项: def self.expires_date_between(from, to) Match.where(:grant_id => Grant.where("expires_at >= ? and expires_at <= ?", from, to)) end 这非常适合根据特定的时间段显示补助金,但补助金不是按日期顺序显示的(过期时间)。看

我的项目和补助金是通过匹配连接起来的。补助金有到期日。我想按授权到期日期对项目的匹配项进行排序

这是根据到期日期为我提供匹配项:

def self.expires_date_between(from, to)
  Match.where(:grant_id => Grant.where("expires_at  >= ? and expires_at <= ?", from, to))
end
这非常适合根据特定的时间段显示补助金,但补助金不是按日期顺序显示的(过期时间)。看起来补助金是按创建日期排序的。如何更改查询,以便按到期日期的顺序列出补助金

我试过:

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
def self.expires\u date\u介于(从,到)

Match.where(:grant\u id=>grant.where(“expires\u at>=”和expires\u at假设您已经在模型中定义了关联,这应该可以工作(但尚未测试):

匹配
.joins(:grant)

.merge(Grant.where(“expires\u at>=”和expires\u at>=”别忘了
BETWEEN
操作符,可以与
where(expires\u at:from..to)
一起使用。谢谢你的提示,这让我的代码更干净了!这非常有效。我还添加了@tadman的建议,最后得到了
匹配。连接(:Grant.merge(Grant.where>)(“过期时间在?和之间?”,从,到)。订单('expires\u at asc')
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
Match
  .joins(:grant)
  .merge(Grant.where("expires_at  >= ? and expires_at <= ?", from, to))
  .order('expires_at asc')