Ruby on Rails get records by highest price
I have a model Rails model called Orders that has a type_id, location, and price. Each type can have multiple orders at the same location with different prices. Check below for a idea of the table structure.
id | type_id | location_id | price
-----------------------------------
1 | 1 | 1 | 12
2 | 1 | 1 | 14
3 | 1 | 1 | 9
4 | 2 | 1 | 1
5 | 2 | 1 | 4
6 | 3 | 1 | 15
7 | 3 | 1 | 7
I am basically wanting to select all the records by type_id using IN
example:
type_ids = "1,2,3"
location_id = 1
Order.find(:all, :conditions => ["location_id = ? and type_id in (?)", location开发者_如何转开发_id, type_ids])
I only want to select the record with the highest price for each type in that location, so the result set would bring back the records with the ID 2, 5 and 6.
I can not seem to work out the find query for this, I hope you understand what I mean. If not ask I can try and explain better.
Cheers
Eef
If you just want the single highest-price for the conditions, you could use
Order.find(:first, :conditions => ["location_id = ? and type_id in (?)", location_id, type_ids], :order => 'price DESC')
...because that query will order the matching records from highest to lowest price, then give you the first record (highest price).
If you want the highest-price item for each type, you're probably breaking out of Rails' query building and using a find_by_sql
to get the max(price)
for each instance of type_id
(something like SELECT *, MAX(price) FROM orders WHERE location_id = ? AND type_id IN (?) GROUP BY type_id
, but I'd want to run that query a few times against your database to refine it, myself).
Unless your number of type_id
s is very large (e.g. in the hundreds) it might be simpler to just run the above query once for each type and put all the results in one array; the MySQL query will be much faster, particularly for large numbers of type_id
s, but doing it in Rails will be Good Enough unless you're determined to get the MAX(price)
query Just Right.
精彩评论