I am trying to number rows from a query so I know which page it will appear on.
My expectation is that the order of the rows returned by the query is the same order they were numbered in--that is, that row_num
will nicely increment in the result set.
However, the GROUP BY
which is causing 2-3 rows to end up out of order (with the GROUP BY
statements removed all numbering is in order).
What happens with GROUP BY
that causes the problem and how do I get row numbering to apply AFTER all the grouping and sorting is done?
SELECT g2.*, @rownum := @rownum + 1 AS row_num
FROM (SELECT g.gemid as gemid, g.tab, rt.sum_rating as sum_rating
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.tab=0 GROUP BY g.gemid) g2
LEFT JOIN gempage gp ON g2.gemid = gp.gemid
JOIN (SELECT @rownum := 0) Z
WHERE g2.tab=0 ORDER BY sort asc