MySql Query: Select top 3 rows from table for each category

前端 未结 3 1529
小蘑菇
小蘑菇 2020-11-30 09:12

I have a table with records and it has a row called category. I have inserted too many articles and I want to select only two articles from each category.

3条回答
  •  醉话见心
    2020-11-30 09:50

    LIMIT only stops the number of results the statement returns. What you're looking for is generally called analytic/windowing/ranking functions - which MySQL doesn't support but you can emulate using variables:

    SELECT x.*
      FROM (SELECT t.*,
                   CASE 
                     WHEN @category != t.category THEN @rownum := 1 
                     ELSE @rownum := @rownum + 1 
                   END AS rank,
                   @category := t.category AS var_category
              FROM TBL_ARTIKUJT t
              JOIN (SELECT @rownum := NULL, @category := '') r
          ORDER BY t.category) x
     WHERE x.rank <= 3
    

    If you don't change SELECT x.*, the result set will include the rank and var_category values - you'll have to specify the columns you really want if this isn't the case.

提交回复
热议问题