如果我只显示数据库中用户的全局排名
,我的代码就可以正常运行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,就像它的全局排名一样。我是否错误地提出了国家条件?我只是不明白我做错了什么。感谢
答案 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 |