MySQL限制行/分组依据

时间:2015-11-08 17:12:26

标签: mysql

我搜索过很多不同的帖子,但我没有找到对我有用的东西。

Using LIMIT within GROUP BY to get N results per group?http://www.sqlines.com/mysql/how-to/get_top_n_each_group对我不起作用。

我有一个简单的MySQL表,其中包含以下列

id , package, user_id, date

我想执行一个查询,我将获得

  

X行/ user_id WHERE日期>按日期编号ASC

简而言之,我们希望使用Group By user_id执行LIMIT of X rows / group,但请记住使用date column

的声明

示例全表

id , package, user_id, date
1,  full, 1 , 1447003159
2,  full, 1 , 1447003055
3,  full, 1 , 1447002022
4,  full, 1 , 1447001013
5,  full, 1 , 1447000031
6,  mid,  2 , 1447003159
7,  mid,  2 , 1447003055
8,  mid,  2 , 1447002022
9,  mid,  2 , 1447001013
10, mid,  2 , 1447000031

从上表中我们只想选择2行/ user_id,但是日期> = 1447000031(但首先要ORDER BY date ASC

预期输出

4,  full, 1 , 1447001013
3,  full, 1 , 1447002022
9,  mid,  2 , 1447001013
8,  mid,  2 , 1447002022

1 个答案:

答案 0 :(得分:3)

E.g:

SELECT x.*
  FROM my_table x 
  JOIN my_table y 
    ON y.id >= x.id 
   AND y.user_id = x.user_id 
 WHERE y.date > 1447000031 
 GROUP 
    BY x.id 
HAVING COUNT(*) <= 2;

或者,更快,但更多的打字...

SELECT id
     , package
     , user_id
     , date 
  FROM 
     ( SELECT x.*
            , CASE WHEN @prev_user = user_id THEN @i:=@i+1 ELSE @i:=1 END rank
            , @prev_user := user_id 
         FROM my_table x
            , ( SELECT @prev_user = 0,@i:=1 ) vars 
        WHERE date > 1447000031
        ORDER 
           BY user_id
        , date
 ) a 
 WHERE rank <= 2;