简体   繁体   中英

Convert SQL query to Active Record query in Rails 4

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")
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM