How to SELECT the newest four items per category?

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

提交回复
热议问题