On MySQL 5.7, you may try something along these lines, using an inner join to restrict to products with the most recent order
value:
SELECT *
FROM product_category AS pc
INNER JOIN categories AS cat ON cat.category_id = pc.category_id
INNER JOIN products AS p ON p.product_id = pc.product_id
INNER JOIN
(
SELECT product_id, MAX(`order`) AS latest_order
FROM products
GROUP BY product_id
) p2
ON p2.product_id = p.product_id AND
p2.latest_order = p.`order`;
The join to the subquery aliased as p2
above restricts to only product records having the latest order
value. Side note: Please avoid naming your columns ORDER
, which is a reserved MySQL keyword.
Edit: A solution for top 5 products per order, ordered by most recent first, using ROW_NUMBER
:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY p.product_id ORDER BY `order` DESC) rn
FROM product_category AS pc
INNER JOIN categories AS cat ON cat.category_id = pc.category_id
INNER JOIN products AS p ON p.product_id = pc.product_id
)
SELECT *
FROM cte
WHERE rn <= 5;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…