我有以下mySQL查询,我想给出在具有相应行位置的计算字段上排序的行。我已经使用来自here的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
答案 0 :(得分:0)
看起来这样有效。我知道在编号之前我必须先对记录进行排序,然后从有序列表中选择SELECT。
SELECT g2.gemid, g2.sum_rating, @rownum := @rownum + 1 AS row_num FROM
(SELECT g.gemid, rt.sum_rating, g.grade FROM gems g
LEFT JOIN (SELECT gemid, SUM(rating) as sum_rating from gemrating GROUP BY gemid) rt ON g.gemid = rt.gemid
WHERE g.grade = '8' ) g2
JOIN (SELECT @rownum := 0) Z
WHERE g2.grade = '8'
ORDER BY sum_rating asc