MySQL - 如何获取行号

时间:2016-05-04 04:04:22

标签: mysql sql row-number

我有这样的表:

tb_bid_test
+-------------+---------------------+
| Field       | Type                |
+-------------+---------------------+
| username    | varchar(20)         |
| poin        | bigint(20)          |
+-------------+---------------------+

然后我运行此查询:

select @r := @r+1 as rank, z.* from(SELECT username, sum(poin) as jumlahPoin FROM `tb_bid_test` GROUP BY username order by jumlahPoin desc limit 3 )z, (select @r:= 0)y;

结果:

+--------+------------+--------------+
| rank   | username   |  jumlahPoin  |
+--------+------------+--------------+
|   1    |        neo |      500     |
|   2    |     andhie |      348     |
|   3    |       john |      123     |
+--------+------------+--------------+

我希望获得1行用户名andhie,如下所示:

+--------+------------+--------------+
| rank   | username   |  jumlahPoin  |
+--------+------------+--------------+
|   2    |      andhie|      348     |
+--------+------------+--------------+

或其他用户名并获得排名,如果我之前使用该代码并添加where username ='andhie'排名始终是1.如何根据他们的积分获得当前排名?

3 个答案:

答案 0 :(得分:1)

从结果用户名中选择值' andhie'

function hash(user) {

    var part1 = mix(user.username, user.password);
    var part2 = mix(user.random_value + salt, user.password);

    return mix(part1, part2);

    function mix(part1, part2) {

        var hash = sha3_256(part1 + part2);

        var rehash = 10000;
        while(rehash--) {
            hash = sha3_256(hash + salt + rehash);
        }
        return hash;
    }

}

Try the fiddle here

答案 1 :(得分:0)

尝试此查询:

Select * from (select @r := @r+1 as rank, z.* from(SELECT username, sum(poin) as jumlahPoin FROM `tb_bid_test` GROUP BY username order by jumlahPoin desc limit 3 )z, (select @r:= 0)y;) where username="andhie"

答案 2 :(得分:0)

使用嵌套查询

SELECT *
FROM (
        SELECT @r := @r + 1 AS rank, z.*
        FROM (
                SELECT username, SUM(poin) AS jumlahPoin
                FROM tb_bid_test
                GROUP BY username
                ORDER BY jumlahPoin 
                DESC limit 3
        ) z,
        (SELECT @r := 0) y
    ) tbl
WHERE username = "andhie"