I am trying to understand how to return a maximum of 5 items for each manufacturer from an inventory table, so that no manufacturer can have more than 5 items shown in a list of 100 recent items at any time. The purpose is to avoid any single manufacturer dominating the list of recent items. The basic query is:
SELECT id, manufacturer_id, product_name, price
FROM inventory_items
WHERE visibility=1 AND availability=1 AND manufacturer_id IN (vw_active_vendor_ids)
ORDER BY creation_datetime DESC LIMIT 0, 100
Conceptually I think I could achieve this by looping through the entire table in a stored procedure, putting the manufacturer id in a temp table and counting them on each loop, but this seems like an expensive operation.
I tried various inner joins and groups but these were completely wrong.
Followed the example here MySQL: how to get x number of results per grouping but the query took > 20 sec to execute which doesn't work for an e-commerce site.
SELECT *, (SELECT manufacturer_name FROM manufacturer WHERE manufacturer.id=t.manufacturer_id) AS manufacturer_name FROM
(SELECT t1.id, t1.manufacturer_id, t1.title, t1.price, t1.creation_datetime , COUNT(*) cnt FROM inventory_items t1
LEFT JOIN inventory_items t2
ON t2.manufacturer_id = t1.manufacturer_id AND t2.id <= t1.id
WHERE t1.availability=1 AND t1.visibility=1
AND t2.availability=1 and t2.visibility=1
AND t1.manufacturer_id IN (SELECT id FROM vw_active_vendor_ids)
AND t2.manufacturer_id IN (SELECT id FROM vw_active_vendor_ids)
GROUP BY
t1.manufacturer_id, t1.id
) t
WHERE
cnt < 6
ORDER BY creation_datetime DESC
LIMIT 0,100