views:

35

answers:

1

Hey,

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

+1  A: 

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_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 of type_ids, but doing it in Rails will be Good Enough unless you're determined to get the MAX(price) query Just Right.

pjmorse
I originaly wrote the application in PHP and I was doing a query to the database for each type, it ran fine. I will never have more than 44 types so I think I may take the simplier approach but I will give the query a bash as well. Thanks for that!
Eef