MySQL Filter result again
The goal here is to 1. find the row with the newest date from each store,
then 2. compare the prices and find the cheapest.
I can accomplish either the first or second goal in separate queries, but
not in the same. How can i filter out a selection and then apply a filter
on the previous result?
//Finding rows with the most current date
SELECT ingredient.name AS ingredient, store.name AS store, brand.name AS
brand, ingredient_price.price, MAX( ingredient_price.date )
FROM ingredient
LEFT OUTER JOIN ingredient_price ON ingredient.ingredient_id =
ingredient_price.ingredient_id
LEFT OUTER JOIN store_to_ingredient_price ON
ingredient_price.ingredient_price_id =
store_to_ingredient_price.ingredient_price_id
LEFT OUTER JOIN store ON store_to_ingredient_price.store_id = store.store_id
LEFT OUTER JOIN brand_to_ingredient_price ON
ingredient_price.ingredient_price_id =
brand_to_ingredient_price.ingredient_price_id
LEFT OUTER JOIN brand ON brand_to_ingredient_price.brand_id = brand.brand_id
GROUP BY ingredient.name
//Finding rows with the cheapest price
SELECT ingredient.name as ingredient, store.name as store, brand.name as
brand, min(ingredient_price.price), ingredient_price.date
FROM ingredient
LEFT OUTER JOIN ingredient_price ON ingredient.ingredient_id =
ingredient_price.ingredient_id
LEFT OUTER JOIN store_to_ingredient_price ON
ingredient_price.ingredient_price_id =
store_to_ingredient_price.ingredient_price_id
LEFT OUTER JOIN store ON store_to_ingredient_price.store_id = store.store_id
LEFT OUTER JOIN brand_to_ingredient_price ON
ingredient_price.ingredient_price_id =
brand_to_ingredient_price.ingredient_price_id
LEFT OUTER JOIN brand ON brand_to_ingredient_price.brand_id = brand.brand_id
GROUP BY ingredient.name
No comments:
Post a Comment