用户的排名正确显示,但在我尝试显示国家排名时则不会

时间:2017-10-03 19:22:18

标签: php mysql rank

如果我只显示数据库中用户的全局排名

,我的代码就可以正常运行
function getUserRank($userId){
    $sql1       = "SET @rownum := 0";

    $sql2       =   "SELECT rank, level FROM (
                    SELECT @rownum := @rownum + 1 AS rank, level, id
                    FROM accounts ORDER BY level DESC
                    ) as result WHERE id=$userId";

    mysql_query($sql1);
    $result = mysql_query($sql2);
    $rows = '';
    $data = array();
    if (!empty($result))
        $rows      =  mysql_num_rows($result);
    else
        $rows      =  '';

    if (!empty($rows)){
        while ($rows = mysql_fetch_assoc($result)){
            $data[]   = $rows;
        }
    }


    if (empty($data[0]['rank']))
        return 1;
    return $data[0]['rank'];  }

但是,如果我修改了第7行WHERE id=$userId, country='".$statsrow['country']."'",那么当每个用户显示每个国家/地区的正常排名时,每个用户都会获得排名1,就像它的全局排名一样。我是否错误地提出了国家条件?我只是不明白我做错了什么。感谢

1 个答案:

答案 0 :(得分:0)

您需要在子查询select子句中包含列country,请参阅此SQL Fiddle作为示例。另请注意,我在下面显示的交叉连接可以帮助您避免需要2个sql语句。

<强>设置

CREATE TABLE accounts
    (`id` int, `level` int, `country` varchar(20))
;

INSERT INTO accounts
    (`id`, `level`, `country`)
VALUES
    (1, 1, 'a'),
    (1, 2, 'a'),
    (3, 1, 'a'),
    (4, 3, 'a'),
    (1, 4, 'a'),
    (6, 1, 'a'),
    (7, 5, 'a')
;

查询1

SELECT rank, level 
FROM (
      SELECT @rownum := @rownum + 1 AS rank, level, id, country
      FROM accounts
      CROSS JOIN (select @rownum := 0 x) var
      ORDER BY level DESC
      ) as result 
WHERE id=1
and country = 'a'

<强> Results

| rank | level |
|------|-------|
|    4 |     2 |
|    5 |     1 |
|    2 |     4 |