There are 5 tables Category, Item, ItemMap, Units and Prices with foreign keys:
Category : category_id, name
Item : item_id, name
ItemMap : category_id, item_id
Prices : category_id, price,currency_code, start_date
Units : item_id, minimum_unit
The requirement is to get the minimum price in each currency out of the latest (but more recent than today) prices of categories that an item is mapped to.
The query below results in a single item and a single price of "eur" as the currency code.
SELECT
item_map.item_id,
units.minimum_unit,
p1.price,
p1.currency_code
FROM item_map
INNER JOIN units ON item_map.item_id = units.item_id
INNER JOIN (
SELECT price,category_id, currency_code, start_date
FROM prices
GROUP BY currency_code
) p1
ON item_map.category_id = p1.category_id
WHERE p1.start_date = (
SELECT max(start_date)
FROM prices
WHERE category_id=p1.category_id AND start_date <= NOW()
);
What am I doing wrong?