ActiveRecord Find - Skipping Records or Getting Every Nth Record

倖福魔咒の 提交于 2019-12-17 19:47:47

问题


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.

Is there any straightforward way to do this with ActiveRecord?


回答1:


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.

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

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

should work.




回答2:


If your Model has an ascending row like id without missing any number you can do something like this:

Model.all(:condition => "models.id%3=0")

If not you can first fetch all rows from the database and then you can do this:

models = Model.all
third_models = models.reject{ |model| models.index(model) % 3 != 0 }


来源:https://stackoverflow.com/questions/3147529/activerecord-find-skipping-records-or-getting-every-nth-record

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