【问题标题】:Rails changing query execution orderRails 更改查询执行顺序
【发布时间】:2014-06-08 17:33:51
【问题描述】:

我想查询前 10 条记录。

所以,我从 Rails 控制台输入:

Log.all.limit(10).where({"username"=>"peeyush"}).explain

这给出了:

Log Load (0.8ms)  SELECT  "logs".* FROM "logs"  WHERE "logs"."username" = 'peeyush' LIMIT 10

显然,LIMIT 10 会在以后发生。

我尝试跑步:

Log.all.first(10).where({"username"=>"peeyush"}).explain

但这会报错:

NoMethodError: undefined method `where' for #<Array:0x0000000539acd8>

应该如何执行查询?

【问题讨论】:

  • where 条件之后你应该给first(10)
  • 那也不行!它提供了一个包含前 10 个日志的数组,其中用户名为 peeyush。
  • 就查询而言,就是输出结果的权利。
  • Log.all.where({"username"=&gt;"peeyush"}).first(10).explain
  • 这给出了错误NoMethodError: undefined method 'explain' for #&lt;Array:0x00000005ba0518&gt;,因为返回值是大小为 10 的数组。此外,它并没有解决我的目的。

标签: sql ruby-on-rails activerecord ruby-on-rails-4


【解决方案1】:

如果我理解正确,您想检索前 10 行,然后按用户名过滤这 10 条记录?

在红宝石中过滤

all.first(10).find_all {|i| i.username == "peeyush" }

对数据库进行过滤

all.where(:id => all.first(10).map {|x| x.id}, :username => "peeyush")

【讨论】:

  • 这应该可以,但我想在数据库中执行过滤,而不是在 Ruby 代码中执行。这样做的一种(不太好的)方法可能是在 id 上再应用一个 where 条件并将 id 限制为前 10 个值,但我正在寻找更好的方法。
  • @Peeyush 刚刚看到您更新的评论,不幸的是我的回答是一样的,但我没有看到其他方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 2022-01-20
  • 2021-10-02
  • 1970-01-01
  • 2014-07-30
  • 1970-01-01
相关资源
最近更新 更多