每组子集的最大行数

时间:2014-09-30 19:39:51

标签: mysql sql greatest-n-per-group

我有这样的查询:

SELECT * FROM user AS u 
JOIN article AS a
ON u.id = a.userid
GROUP BY u.id

如何为每个特定用户提取最多10篇文章?

1 个答案:

答案 0 :(得分:0)

Mysql没有针对此类结果的窗口函数另一种解决方法是使用用户定义的变量来获得每组的n个结果

SELECT * FROM (
SELECT a.*,
@r:= CASE WHEN @g = userid THEN @r + 1 ELSE 1 END row_num,
@g:= userid
FROM (SELECT * 
FROM `user` AS u 
JOIN article AS a
ON u.id = a.userid
ORDER BY u.id,a.id DESC
) a
CROSS JOIN (SELECT @g:=NULL,@r:0) b
) t
WHERE row_num <=10