views:

199

answers:

1

I've got the following 2 tables:

  • ingredients (id, name)
  • ingredient_prices (id, ingredient_id, price, created_at)

such that one ingredient can have many prices. What will be the best way to get the latest entered price per ingredient? I know it can be done easily with sub-selects, but I want to know if there is a more efficient way for doing it.

+3  A: 

I do it this way:

SELECT i.*, p1.*
FROM ingredients i
 JOIN ingredient_prices p1 ON (i.id = p1.ingredient_id)
 LEFT OUTER JOIN ingredient_prices p2 ON (i.id = p2.ingredient_id 
   AND p1.created_at < p2.created_at)
WHERE p2.id IS NULL;

This searches for a price (p2) that is more recent than p1, and if none is found, then p1 must be the most recent price.

If there is a possibility of more than one price on a given date, then you need another term to filter out the duplicate.

Bill Karwin