用ActiveRecord如何选择基于字段的最高值的记录? [英] with activerecord how can I select records based on the highest value of a field?

查看:255
本文介绍了用ActiveRecord如何选择基于字段的最高值的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些我不知道该怎么做的活动记录(其实我自己也说不清楚到底如何使用SQL做),我想这样做。我想选择一个基于某一领域的最高值以及其他一些条件的记录。下面是一些伪东西,这也解释了我的处境。鉴于以下记录:

  ID:1 |名称:RECIPE1 |保存:真|修订:1
编号:2 |名称:RECIPE1 |保存:假|修订:2
ID:3 |名称:RECIPE1 |保存:真|修订:3
ID:4 |名称:RECIPE1 |保存:假|修订版:4
ID:5 |名称:recipe2 |保存:真|修订:1
ID:6 |名称:recipe2 |保存:真|修订:2
ID:7 |名称:recipe3 |保存:假|修订:1
ID:8 |名称:recipe4 |保存:真|修订:1
 

我希望能够得到与已保存的最高版本号的记录。这将意味着与IDS记录:3,6和8

我的第一反应是做一些类型的子查询,获取一个MAX上修改或东西。除此之外,我真的没有任何想法如何去那所以任何帮助将大大AP preciated。

编辑:

这就是我想要做什么的SQL:

  SELECT ID,姓名,MAX(修订版)的修订版FROM修订WHERE保存= 1 GROUP BY名称
 

现在,没有任何合理的方式与ActiveRecord的做到这一点?

解决方案

  Revision.maximum(:修订:条件=>保存= 1],:组=&GT ; '名称')
 

I have run into something I don't know how to do with active record (actually I couldn't say exactly how to do it with sql) that I would like to do. I would like to select records based on the highest value of a certain field as well as some other criteria. Below is some pseudo stuff which explains my situation. Given the following records:

id:1 | name:recipe1 | saved:true  | revision:1
id:2 | name:recipe1 | saved:false | revision:2
id:3 | name:recipe1 | saved:true  | revision:3
id:4 | name:recipe1 | saved:false | revision:4
id:5 | name:recipe2 | saved:true  | revision:1
id:6 | name:recipe2 | saved:true  | revision:2
id:7 | name:recipe3 | saved:false | revision:1
id:8 | name:recipe4 | saved:true  | revision:1

I would like to be able to get the records with the highest revision number that has been saved. That would mean records with ids: 3, 6, and 8

My first instinct is to do some kind of subquery that gets a MAX on revision or something. Other than that, I don't really have any idea how to go about that so any help will be greatly appreciated.

EDIT:

this is the sql that does what I want:

SELECT id, name, MAX(revision) as "revision" FROM revisions WHERE saved = 1 GROUP BY name

Now, is there any reasonable way to do this with ActiveRecord?

解决方案

Revision.maximum(:revision,:conditions => ["saved=1"],:group => 'name')

这篇关于用ActiveRecord如何选择基于字段的最高值的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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