本文介绍了SQL查询转换为Rails中4活动记录查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SELECT *
从 (
SELECT DISTINCT ON(秒)
ID,秒
从任务
ORDER BY秒,ID DESC
)子
ORDER BY ID DESC
LIMIT 4;
我想知道如果上面的SQL查询可以被转换成一个Active Record的查询。现在我使用的find_by_sql
如下:
Task.find_by_sql(SELECT * FROM(SELECT DISTINCT ON(SEC)的ID,证券交易委员会的任务ORDER BY秒,ID DESC)子ORDER BY ID DESC LIMIT 4)
解决方案
Task.select('T *'。)从(Task.distinct(:秒)。选择(: ID,:秒)。集团(:秒).order('秒,ID降序):T).order('身份证降序)的限制(4)
或只是做它组只(不同的不需要)
Task.select('T *'。)从(Task.select(:ID,:秒)。集团(:秒).order('秒,ID说明' ):T).order('身份证降序)的限制(4)
这AR查询将分成2 SQL查询,主副查询。子查询将检索重复的记录:秒属性值和主查询将责令其按降序标识和限制的记录,以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
这篇关于SQL查询转换为Rails中4活动记录查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!