Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

sql - with activerecord how can I select records based on the highest value of a field?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Revision.maximum(:revision,:conditions => ["saved=1"],:group => 'name')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...