嘿,我试图从指定的玩家ID获得等级。
我使用phpMyAdmin MySQL InnoDB和PHP。
我有两个人有数据库。
Userdatabase有一个名为users的表。 该表有5个字段:id,username,email,password和date。
第二个数据库称为分数,每个级别有一个表。 所有表格都有相同的字段:id,score,time,bonus,timestamp。
我立即连接到乐谱数据库:
$conn = mysqli_connect($host, $user, $pass, $mysql_db);
$multisql .= "SET @rank := 0;";
$multisql .= "SELECT *, @rank := @rank + 1 AS rank FROM $table AS s
LEFT JOIN userdatabase.users AS u ON s.id = u.id
ORDER BY score DESC, timestamp ASC LIMIT 10;";
此查询返回所有具有正确排名的条目,但我只想要一个id为$ userid的条目,所以我尝试:
$multisql .= "SET @rank := 0;";
$multisql .= "SELECT *, @rank := @rank + 1 AS rank FROM $table AS s
LEFT JOIN userdatabase.users AS u ON s.id = u.id
WHERE u.id = $userid
ORDER BY score DESC, timestamp ASC LIMIT 10;";
这仅返回指定的用户结果,但等级始终为1.
我尝试将Select包装在另一个选择中,但是我没有得到这样的结果。
$multisql .= "SET @rank := 0;";
$multisql .= "SELECT * FROM (
SELECT *, @rank := @rank + 1 AS rank FROM $table AS s
LEFT JOIN userdatabase.users AS u ON s.id = u.id
ORDER BY score DESC, timestamp ASC
) rank WHERE id = $userid;";
我尝试过上述示例的一些不同变体,但没有任何效果。我非常确定应该有两个SELECT接一个。我尝试按照post的答案来接近我之后的答案。
感谢任何帮助!
答案 0 :(得分:0)
运行实验,使用不同的表格和列,但有效地使用您的最终查询似乎会产生您正在寻找的结果。
首先是用于显示测试表中所有记录和所有已定义列的基本查询
mysql>select * from `customers`;
+----+---------------------+-------------------+
| id | cust_name | cust_address |
+----+---------------------+-------------------+
| 0 | Charlie Farnsbarnse | Alpha Centauri |
| 1 | Joe Bloggs | Nowhere Important |
| 2 | Fred SMith | Somewhere else |
| 3 | Barney Gumble | Brooklyn |
| 4 | Betty Boop | Hollywood |
+----+---------------------+-------------------+
然后,在设置变量后运行一个新查询以显示每个变量的等级。
mysql>set @id=4;
set @rank := 0;
select *, @rank := @rank + 1 as 'rank' from `customers`;
+----+---------------------+-------------------+------+
| id | cust_name | cust_address | rank |
+----+---------------------+-------------------+------+
| 0 | Charlie Farnsbarnse | Alpha Centauri | 1 |
| 1 | Joe Bloggs | Nowhere Important | 2 |
| 2 | Fred SMith | Somewhere else | 3 |
| 3 | Barney Gumble | Brooklyn | 4 |
| 4 | Betty Boop | Hollywood | 5 |
+----+---------------------+-------------------+------+
最后,由where子句强加的额外约束只返回一个具有上一个查询中所见等级的记录。
mysql>set @rank := 0;
select * from (
select *, @rank := @rank + 1 as 'rank' from `customers` as s
) rank where id = @id;
+----+------------+--------------+------+
| id | cust_name | cust_address | rank |
+----+------------+--------------+------+
| 4 | Betty Boop | Hollywood | 5 |
+----+------------+--------------+------+
这是从命令行运行的,但是我没有理由在替换到你的sql时使用PHP变量$userid
失败。