Convert SQL query to Active Record query in Rails 4

本小妞迷上赌 提交于 2019-12-13 04:41:29

问题


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

I am wondering if the above SQL query can be converted to an Active Record query. For now I am using find_by_sql as follows:

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:


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

or just do it with group by only (distinct not needed)

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

This AR query will split into 2 sql queries, main and sub queries. Sub query will retrieve distinct records on :sec attribute value and main query will order them in descending ids and limit records to 4



来源:https://stackoverflow.com/questions/22945508/convert-sql-query-to-active-record-query-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!