How to SELECT the newest four items per category?

前端 未结 8 2261
被撕碎了的回忆
被撕碎了的回忆 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:14

    Depending on how constant your categories are, the following is the simplest route

    SELECT C.CategoryName, R.Image, R.date_listed
    FROM
    (
        SELECT CategoryId, Image, date_listed
        FROM 
        (
          SELECT CategoryId, Image, date_listed
          FROM item
          WHERE Category = 'Pet Supplies'
          ORDER BY date_listed DESC LIMIT 4
        ) T
    
        UNION ALL
    
        SELECT CategoryId, Image, date_listed
        FROM
        (        
          SELECT CategoryId, Image, date_listed
          FROM item
          WHERE Category = 'Pet Food'
          ORDER BY date_listed DESC LIMIT 4
        ) T
    ) RecentItemImages R
    INNER JOIN Categories C ON C.CategoryId = R.CategoryId
    ORDER BY C.CategoryName, R.Image, R.date_listed
    
    0 讨论(0)
  • 2020-11-22 02:15

    the code below shows a way to do it in a loop it definetely needs a lot of editing, but i hope it helps.

            declare @RowId int
     declare @CategoryId int
            declare @CategoryName varchar(MAX)
    
     create table PART (RowId int, CategoryId int, CategoryName varchar)
     create table  NEWESTFOUR(RowId int, CategoryId int, CategoryName varchar, Image image)
            select RowId = ROW_NUMBER(),CategoryId,CategoryName into PART from [Category Table]
    
    
            set @PartId = 0
     set @CategoryId = 0 
     while @Part_Id <= --count
     begin
       set @PartId = @PartId + 1
              SELECT @CategoryId = category_id, @CategoryName = category_name from PART where PartId = @Part_Id
              SELECT RowId = @PartId, image,CategoryId = @category_id, CategoryName = @category_name   FROM item into NEWESTFOUR where category_id = :category_id 
    ORDER BY date_listed DESC LIMIT 4
    
     end
     select * from NEWESTFOUR
     drop table NEWESTFOUR
            drop table PART
    
    0 讨论(0)
  • 2020-11-22 02:20

    This is the greatest-n-per-group problem, and it's a very common SQL question.

    Here's how I solve it with outer joins:

    SELECT i1.*
    FROM item i1
    LEFT OUTER JOIN item i2
      ON (i1.category_id = i2.category_id AND i1.item_id < i2.item_id)
    GROUP BY i1.item_id
    HAVING COUNT(*) < 4
    ORDER BY category_id, date_listed;
    

    I'm assuming the primary key of the item table is item_id, and that it's a monotonically increasing pseudokey. That is, a greater value in item_id corresponds to a newer row in item.

    Here's how it works: for each item, there are some number of other items that are newer. For example, there are three items newer than the fourth newest item. There are zero items newer than the very newest item. So we want to compare each item (i1) to the set of items (i2) that are newer and have the same category as i1. If the number of those newer items is less than four, i1 is one of those we include. Otherwise, don't include it.

    The beauty of this solution is that it works no matter how many categories you have, and continues working if you change the categories. It also works even if the number of items in some categories is fewer than four.


    Another solution that works but relies on the MySQL user-variables feature:

    SELECT *
    FROM (
        SELECT i.*, @r := IF(@g = category_id, @r+1, 1) AS rownum, @g := category_id
        FROM (@g:=null, @r:=0) AS _init
        CROSS JOIN item i
        ORDER BY i.category_id, i.date_listed
    ) AS t
    WHERE t.rownum <= 3;
    

    MySQL 8.0.3 introduced support for SQL standard window functions. Now we can solve this sort of problem the way other RDBMS do:

    WITH numbered_item AS (
      SELECT *, ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY item_id) AS rownum
      FROM item
    )
    SELECT * FROM numbered_item WHERE rownum <= 4;
    
    0 讨论(0)
  • 2020-11-22 02:20

    ok after a googling the quick answer would it's not possible at least on mysql

    this this thread for reference

    maybe you should cache the result of that query if you are afraid to make fall down the server and you want the code to perform more well

    0 讨论(0)
  • 2020-11-22 02:25

    not very pretty but:

    SELECT image 
    FROM item 
    WHERE date_listed IN (SELECT date_listed 
                          FROM item 
                          ORDER BY date_listed DESC LIMIT 4)
    
    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题