首页  编辑  

Mysql中取某个字段对不同数据取前N条记录

Tags: /MySQL/   Date Created:

MySQL select top N rows for each category

MySQL中取字段数据前N条记录

表格:
  Id   | category_id | created_at
------ | -----------   ----------
   1   |      1      | 2017-12-01
   2   |      2      | 2017-12-02
   3   |      4      | 2017-12-03
   4   |      2      | 2017-12-04
   5   |      1      | 2017-12-05
   6   |      1      | 2017-12-06
   7   |      3      | 2017-12-07
   8   |      4      | 2017-12-08
   9   |      4      | 2017-12-09
   10  |      3      | 2017-12-10
   11  |      5      | 2017-12-11

预期结果:
      Ids     
    ------ 
       5   
       6   
       2   
       4   
       7
       10
       8
       9
       11
查询语句:
SELECT *
   FROM
     (SELECT *, 
                  @count := IF(@current_category = category_id, @count + 1, 1) AS count,
                  @current_category := category_id 
       FROM table
       ORDER BY category_id, created_at DESC
     ) ranked
   WHERE count <= 2;