sql - 基于列的@curRow

时间:2017-01-04 21:27:16

标签: mysql sql indexing

我正在创建排名系统,所以我需要为每个用户设置排名位置 我这样做:

SELECT  @curRow := @curRow + 1 AS position,
                Sum(point_user.amount) AS points
FROM        users u
JOIN        point_user ON u.id = point_user.user_id
JOIN    (SELECT @curRow := 0) r
GROUP BY
u.id
ORDER BY
position ASC

我得到了:

+----------+----------+
| position | points   |
+----------+----------+
|        1 | 86       |
|        2 | 239      |
|        3 | 45       |
+----------+----------+

现在,如何根据点设置行号?
应该看起来像:

+----------+----------+
| position | points   |
+----------+----------+
|        1 | 239      |
|        2 | 86       |
|        3 | 45       |
+----------+----------+

更新

SELECT (@curRow := @curRow + 1) as position, 
                points, 
                u2.id
FROM (SELECT Sum(pu.amount) AS points
      FROM users u JOIN
           point_user pu
           ON u.id = pu.user_id
      GROUP BY u.id
      ORDER BY points DESC
) upu, users u2
CROSS JOIN (
            SELECT @curRow := 0
) params
ORDER BY points DESC

1 个答案:

答案 0 :(得分:3)

在您的查询中,将ORDER BY更改为ORDER BY points DESC可能就足够了 - 因为这似乎是您的意图。

但是,MySQL存在变量和GROUP BY的已知问题。解决方案只是使用子查询:

SELECT (@curRow := @curRow + 1) as position, points
FROM (SELECT Sum(pu.amount) AS points
      FROM users u JOIN
           point_user pu
           ON u.id = pu.user_id
      GROUP BY u.id
      ORDER BY points DESC
     ) upu CROSS JOIN
     (SELECT @curRow := 0) params
ORDER BY points DESC;