Select 2 products from each category in MySQL

后端 未结 3 556

Pretty similar to MYSQL - select first 4 records for each category in a table but there isn\'t an accepted answer and the one answer there doesn\'t make much sense so i\'m a

3条回答
  •  甜味超标
    2020-12-21 06:58

    This should do what you are looking for.

    SET @I=0; 
    SET @C='';
    SELECT ID, Name, Category FROM (
        SELECT B.*, 
        IF(@C != B.Category, @I:=1, @I:=@I+1) AS RowNum,
        @C:=B.Category
        FROM (
            SELECT ID, Name, Category FROM Products GROUP BY Name, Category ORDER BY Category
        ) AS B HAVING RowNum <= 2
    ) AS A
    

提交回复
热议问题