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

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

问题描述

我遇到了一些我不知道如何处理活动记录的事情(实际上我无法确切地说如何使用 sql 做到这一点),我想这样做.我想根据某个字段的最高值以及其他一些标准来选择记录.下面是一些解释我的情况的伪内容.鉴于以下记录:

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

我希望能够获得已保存的具有最高修订号的记录.这意味着 id 为 3、6 和 8 的记录

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

我的第一直觉是做某种子查询,在修订版或其他方面获得 MAX.除此之外,我真的不知道如何去做,所以任何帮助将不胜感激.

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.

这是执行我想要的操作的 sql:

this is the sql that does what I want:

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

现在,有没有什么合理的方法可以用 ActiveRecord 做到这一点?

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

推荐答案

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

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

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