请查看以下SQL小提琴。
http://sqlfiddle.com/#!2/f7939/3
您将看到我的查询:
SELECT sub.entry_id, sum(jud.stage), sub.category_id, sub.member_group
FROM exp_judging AS jud
LEFT JOIN exp_submissions AS sub ON jud.rel_id = sub.id
WHERE jud.rel_id = jud.rel_id
GROUP BY jud.rel_id
ORDER BY 3 ASC
LIMIT 10
这是将具有相同rel_id的所有行添加到一起,然后输出它们。
我只需要输出每个类别的前x个数字,现在让我们从每个类别中输出3个。
举个例子,我的SQL Fiddle的结果是:
第1类:(按分数顺序的entry_id) 10,11,16
第2类: 13,12,14
我怎样才能做到这一点?
答案 0 :(得分:2)
虽然我确信必须有更清晰的解决方案,但您可以使用row number
引入user defined variables
来实现此目标:
SELECT *
FROM (
SELECT *,
@rn:=IF(@prevCat=category_id, @rn + 1,1) rn,
@prevCat:=category_id
FROM (
SELECT sub.entry_id,
sum(jud.stage),
sub.member_group,
sub.category_id
FROM exp_judging AS jud
LEFT JOIN exp_submissions AS sub ON jud.rel_id = sub.id
GROUP BY jud.rel_id
ORDER BY sub.category_id, sum(jud.stage) DESC, sub.entry_id
) T
JOIN (SELECT @rn:=0, @prevCat:=0) T2
) T
WHERE rn <= 3