I have a database of items. Each item is categorized with a category ID from a category table. I am trying to create a page that lists every category, and underneath each
In other databases you can do this using the ROW_NUMBER
function.
SELECT
category_id, image, date_listed
FROM
(
SELECT
category_id, image, date_listed,
ROW_NUMBER() OVER (PARTITION BY category_id
ORDER BY date_listed DESC) AS rn
FROM item
) AS T1
WHERE rn <= 4
Unfortunately MySQL does not support the ROW_NUMBER
function, but you can emulate it using variables:
SELECT
category_id, image, date_listed
FROM
(
SELECT
category_id, image, date_listed,
@rn := IF(@prev = category_id, @rn + 1, 1) AS rn,
@prev := category_id
FROM item
JOIN (SELECT @prev := NULL, @rn = 0) AS vars
ORDER BY category_id, date_listed DESC
) AS T1
WHERE rn <= 4
See it working online: sqlfiddle
It works as follows: