How to SELECT the newest four items per category?

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

提交回复
热议问题