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
…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_sqlto get themax(price)for each instance oftype_id(something likeSELECT *, 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_ids 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 oftype_ids, but doing it in Rails will be Good Enough unless you’re determined to get theMAX(price)query Just Right.