Select 2 products from each category in MySQL

后端 未结 3 555

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:23

    FULL SQL:

    SELECT t.id, t.name, t.category
    FROM the_table AS t
    , (SELECT MIN(id) AS id_min FROM the_table GROUP BY category) AS t1
    , (SELECT MAX(id) AS id_max FROM the_table GROUP BY category) AS t2
    WHERE (t.id=t1.id_min) OR  (t.id=t2.id_max)
    

    The query picks the min and the max of each category and return both of them (or only one if it is the same).

    You said "The order of the selected products is of no importance, they might as well be random", so this method should be ok.

提交回复
热议问题