Select 2 products from each category in MySQL

后端 未结 3 553

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 07:11

    Something along these lines will work:

    SELECT id, name, category 
    FROM (
      SELECT *, 
             IF( @prev <> category, 
                 @rownum := 1, 
                 @rownum := @rownum+1 
             ) AS rank, 
             @prev := category, 
             @rownum  
      FROM (
        SELECT * FROM products 
        ORDER BY category, rand()
      ) random_prodcts
    ) products_ranked 
    WHERE rank <= 2;
    

    It orders them randomly within the categories, then pulls them out tracking how many it's got from each.

    Not sure how nicely it will scale though.

    EDIT: Tried it with a few thousand records and it seems ok.

提交回复
热议问题