MySql在每个组中获得前n个

时间:2015-07-07 23:49:06

标签: mysql

我写了一个查询,如:

select title, userId, created_at, deviceCode, streamTimeInSecond
from ( select title, userId, created_at, deviceCode, streamTimeInSecond,
          @userId_rank:=IF(@current_userId = userId, @userId_rank + 1, 1) as userId_rank, 
          @current_userId:=userId 
   from ViewforfirstfiveMovies order by userId, streamTimeInSecond desc ) ranked
where userId_rank<=5;

在这个查询中,我试图获得数据库中每个userId查看的5个标题。 问题:我为少数用户提供了超过5条记录。

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

MySQL不保证select中表达式的评估顺序。因此,您只应在单个表达式中设置相互关联的变量。

我会把它写成:

select title, userId, created_at, deviceCode, streamTimeInSecond
from (select title, userId, created_at, deviceCode, streamTimeInSecond,
              (@userId_rank := if(@current_userId = userId, @userId_rank + 1,
                                  if(@current_userId := userId, 1, 1)
                                 )
               ) as userId_rank,
      from ViewforfirstfiveMovies cross join
           (select @current_userId := 0, @userId_rank := 0) params
      order by userId, streamTimeInSecond desc
     ) ranked
where userId_rank <= 5;

此外,您应该在同一语句中设置变量。