How to SELECT the newest four items per category?

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

    Recently I came across a similar situation, I tried a query that worked for me which is independent on database

    SELECT i.* FROM Item AS i JOIN Category c ON i.category_id=c.id WHERE
    (SELECT count(*) FROM Item i1 WHERE 
    i1.category_id=i.category_id AND 
    i1.date_listed>=i.date_listed) <=3 
    ORDER BY category_id,date_listed DESC;
    

    It is equivalent to running 2 for loops and checking if items newer than this are less than 3

提交回复
热议问题