How to SELECT the newest four items per category?

前端 未结 8 2254
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 01:43

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

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:28

    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:

    • Intially @prev is set to NULL, and @rn is set to 0.
    • For each row we see, check if the category_id is the same as the previous row.
      • If yes, increment the row number.
      • Otherwise start a new category and reset the row number back to 1.
    • When the subquery completes, the final step is to filter so that only rows with row number less than or equal to 4 are kept.

提交回复
热议问题