带ORDER BY的MySQL行号

时间:2018-09-02 12:18:53

标签: mysql sql

现在我有这个:

SELECT
@rownum := @rownum + 1 AS rownum,
T1.*
FROM
(
    SELECT user.username, points
    FROM scores
    JOIN users AS user ON user.id = scores.user_id
) AS T1, (SELECT @rownum := 0) AS r
ORDER BY T1.points DESC, rownum ASC

这将返回用户名,点和行号。点是有序的,但行号都弄乱了。如果我将ORDER BY放入嵌套的select中,那么将对行数字键进行排序,但对点不进行排序。因此,我需要进行更改,以使积分以降序排列,而行号则以升序排列,我要创建的是排行榜,以便用户将多数积分排在第一等。

mysql return

2 个答案:

答案 0 :(得分:2)

您似乎需要将rownum与已预订的points配对。因此,您需要将ORDER BY上的points移到嵌套的select中:

SELECT
@rownum := @rownum + 1 AS rownum,
T1.*
FROM
(
    SELECT user.username, points
    FROM scores
    JOIN users AS user ON user.id = scores.user_id
    ORDER BY points DESC
) AS T1, (SELECT @rownum := 0) AS r
ORDER BY rownum ASC

答案 1 :(得分:0)

这是您想要的吗?

SELECT (@rownum := @rownum + 1) AS rownum,
       us.*
FROM (SELECT u.username, s.points
      FROM scores s JOIN
           users u
           ON u.id = s.user_id
      ORDER BY s.points DESC
     ) us CROSS JOIN
     (SELECT @rownum := 0) params;

基本上,这只是将排序保留在子查询中。

如果points不是数字,则在子查询中使用ORDER BY (s.points + 0) DESC。或修复数据,以便将其存储为数字。