[英]MySql Get top n in each group
我寫了一個查詢,像:
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條以上的記錄。
請幫助我解決這個問題。
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;
另外,您應該在同一條語句中設置變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.