我有以下 mySQL 查询,我想给在计算字段上排序的行以及相应的行位置。我已使用此处的 OMG Ponies 代码作为模板,但返回的行编号不正确(它们在没有排序的情况下按键(gemid)顺序编号)。我知道这与 GROUP BY 上的 JOIN 有关,但我知道如何解决它。提前致谢。
SELECT g.gemid, sum_rating, @rownum := @rownum + 1 AS row_num FROM gems g
LEFT JOIN (SELECT gemid, SUM(rating) as sum_rating from gemrating GROUP BY gemid) rt ON g.gemid = rt.gemid
JOIN (SELECT @rownum := 0) Z
WHERE g.grade = '8'
ORDER BY sum_rating asc
输出应该看起来像:
gemid sum_rating row_num
------ ------------ ----------
2 10 1
4 25 2
1 40 3
3 41 4
相反,它又回来了:
gemid sum_rating row_num
------ ------------ ----------
2 10 2
4 25 4
1 40 1
3 41 3