MySQL get row position with ORDER BY incorrectly numbered

╄→尐↘猪︶ㄣ 提交于 2019-12-11 21:27:33

问题


I have the following mySQL query which I want to give the rows sorted on a calculated field with the corresponding row position. I've used OMG Ponies code from here as a template but the rows are coming back incorrectly numbered (they are being numbered in key (gemid) order without the sort). I know it has to do with the JOIN on a GROUP BY but I know know how to fix it. Thanks in advance.

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

The output should come back looking like:

gemid    sum_rating    row_num
------   ------------  ----------
2           10           1
4           25           2
1           40           3
3           41           4

Instead it is coming back:

gemid    sum_rating    row_num
------   ------------  ----------
2           10           2
4           25           4
1           40           1
3           41           3

回答1:


Looks like this works. I knew I had to sort the records first before numbering them, and then SELECT from the ordered list.

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


来源:https://stackoverflow.com/questions/19721651/mysql-get-row-position-with-order-by-incorrectly-numbered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!