在Rails 4中将SQL查询转换为Active Record查询

时间:2014-04-08 18:37:10

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

SELECT *
FROM (
   SELECT DISTINCT ON (sec)
          id, sec
   FROM   tasks
   ORDER  BY sec, id DESC
   ) sub
ORDER  BY id DESC
LIMIT  4;

我想知道上述SQL查询是否可以转换为Active Record查询。目前我正在使用find_by_sql,如下所示:

Task.find_by_sql("SELECT * FROM ( SELECT DISTINCT ON (sec) id, sec FROM tasks ORDER BY sec, id DESC ) sub ORDER BY id DESC LIMIT 4")

1 个答案:

答案 0 :(得分:0)

Task.select('t.*').from(Task.distinct(:sec).select(:id, :sec).group(:sec).order('sec, id desc'), :t).order('id desc').limit(4)

或者仅使用group by(不需要,不需要)

Task.select('t.*').from(Task.select(:id, :sec).group(:sec).order('sec, id desc'), :t).order('id desc').limit(4)

此AR查询将拆分为2个sql查询,主查询和子查询。子查询将检索不同的记录:sec属性值和主查询将按降序ID排序它们并将记录限制为4