ActiveRecord Find - 跳过记录或获取每 N 个记录 [英] ActiveRecord Find - Skipping Records or Getting Every Nth Record

查看:11
本文介绍了ActiveRecord Find - 跳过记录或获取每 N 个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个查询,在其中选择一堆数据,但我希望能够通过仅选择(例如,每三条记录,甚至每百条记录)来降低该数据的分辨率记录,或其他.

I'd like to do a query where I select a bunch of data, but I'd like to be able to then decrease the resolution of that data by only selecting, say, every third record, or maybe even every hundredth record, or whatever.

有没有什么简单的方法可以用 ActiveRecord 做到这一点?

Is there any straightforward way to do this with ActiveRecord?

推荐答案

在 Oracle 中,我会这样写:

In Oracle i would write that as follows:

YourModel.find(:conditions => 'MOD(ROWNUM,3) = 0') 

这样做的好处是过滤器发生在数据库中,因此不会检索到所有内容.

this has the advantage that the filter happens at the database, so not everything is retrieved.

在 PostgreSQL 中,这称为 ROW_NUMBER(实际上这是 SQL 标准).在 MySQL 中,这是不支持的.

In PostgreSQL this is called ROW_NUMBER (actually that is the SQL-standard). In MySQL this is not supported.

在 mysql 中,您可以使用 SELECT @rownum:=@rownum+1 rownum, t.* FROM (SELECT @rownum:=0) r, mytable t; 来模拟 rownum.所以我想像

In mysql you can mimic rownum using SELECT @rownum:=@rownum+1 rownum, t.* FROM (SELECT @rownum:=0) r, mytable t;. So i guess something like

Bar.find_by_sql("select * from (SELECT @rownum:=@rownum+1 rownum, t.* FROM (SELECT @rownum:=0) r, mytable t) where mod(rownum,3) = 0") 

应该可以.

这篇关于ActiveRecord Find - 跳过记录或获取每 N 个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆