| id | fb_uid | fb_full_name | ---------------------------- | 1 | 101 | user_101 | | 2 | 102 | user_102 | | 3 | 103 | user_103 | | 4 | 104 | user_104 |
| id | user_id | cat_id | score | ------------------------------- | 1 | 101 | 1 | 100 | | 2 | 102 | 1 | 200 | | 3 | 101 | 2 | 300 | | 4 | 104 | 1 | 450 | | 5 | 103 | 1 | 500 | -------------------------------
MySQL& PHP:我们如何得到:
| Rank | Name | score | ------------------------------ | 1 | user_103 | 500 | | 2 | user_104 | 450 | | 3 | user_101 | 400 | | 4 | user_102 | 200 |
答案 0 :(得分:1)
试试这个:
SELECT
@rank := @rank + 1 AS Rank,
u.fb_full_name,
SUM(us.score) AS new_score
FROM userscore us INNER JOIN tbluser u ON us.user_id = u.id
CROSS JOIN (SELECT @rank := 0) param
ORDER BY new_score DESC
答案 1 :(得分:0)
你应该试试这个:
SELECT @r := 0;
SELECT @r := @r + 1 AS Rank,u.fb_full_name AS Name,SUM(us.score) AS Score
FROM userscore as us
INNER JOIN tbluser as u ON us.user_id = u.fb_uid
ORDER BY new_score DESC;
答案 2 :(得分:0)
这是纯SQL。
select count(us2.user_id)+1 rank, u.fb_full_name, us.score
from tbluser u
join (
select user_id, sum(score) score
from userscore
group by user_id
) us on us.user_id = u.fb_uid
left join (
select user_id, sum(score) score
from userscore
group by user_id
) us2 on us2.score > us.score
group by u.fb_full_name, us.score
order by rank, us.user_id
如果两个玩家具有相同的分数,则他们会获得相同的等级,并且将跳过下一个等级,例如
1 user1 500
2 user2 400
2 user3 400
4 user4 300
但使用
在PHP中对用户进行排名要容易得多select u.fb_full_name, sum(us.score) score
from tbluser u
join userscore us on us.user_id = u.fb_uid
group by u.fb_full_name
order by score desc, u.id
等等
$users = array();
$i = 0;
while ($row = $result->fetchAssoc()) {
$row['rank'] = ++$i;
$users[] = $row;
}
或
$users = array();
$lastScore = null;
$lastRank = 1;
$rank = 0;
while ($row = $result->fetchAssoc()) {
++$rank;
if ($row[score] !== $lastScore) {
$lastRank = $rank;
}
$row[rank] = $lastRank;
$users[] = $row;
}
答案 3 :(得分:0)
您必须在查询中使用JOIN,如下所示:
SELECT tbluser.fb_full_name, SUM(userscore.score) AS userscore FROM tbluser
JOIN userscore ON tbluser.fb_uid = userscore.user_id
GROUP BY tbluser.fb_uid
ORDER BY userscore DESC;
在此处查看您的示例的实现。