获取SQL结果中的行号

时间:2013-09-16 12:32:15

标签: mysql

 SELECT a.userid, u.name, u.profilePic , 
   SUM(activity_weight) AS totalPoints, 
  (SELECT @rank:=1 +1) AS rank
 FROM activity_entries a 
 INNER JOIN users1 u ON u.id = a.userid 
 WHERE competitionId = '5216078af3730' 
 GROUP BY a.userid 
 ORDER BY totalPoints DESC

所以我有这个SQL查询效果很好,我按照自己的意愿返回totalPoints,但我也希望得到每个结果的排名/行位置。

目前上面的查询返回每行的等级2,显然没有正确递增。

会喜欢一些帮助/建议!

Ĵ

1 个答案:

答案 0 :(得分:2)

试试这个:

(SELECT @rank:=@rank +1)

对于每一行,您刚添加1 + 1,总是2。

修改

您需要初始化变量:

SET @rank=0;

您需要在使用相同连接之前执行此查询。

SELECT
    tmp.userid,
    tmp.name,
    tmp.profilePic,
    tmp.totalPoints,
    (SELECT @rank:=@rank +1) AS rank
FROM (
    SELECT 
        a.userid, 
        u.name, 
        u.profilePic , 
        SUM(activity_weight) AS totalPoints
    FROM 
        activity_entries a 
    INNER JOIN users1 u 
        ON u.id = a.userid 
    WHERE 
        competitionId = '5216078af3730' 
    GROUP BY 
        a.userid 
    ORDER BY 
        totalPoints DESC
) as tmp