我有一张我想要显示的结果表:
| change | position | name | score |
|----------------------------------|
| - | 1 | Bob | 10 |
| +1 | 2 | Tom | 8 |
| -1 | 3 | Sam | 7 |
|----------------------------------|
更改列反映了人的位置移动,因此从第3移动到第2是+1,从第2移到第3是-1等。所以在上面的例子中,自从上一场比赛汤姆已经超过了Sam。
我可以编写一个提供结果的SQL语句,包括“更改”列吗?
现在我正在编写两个查询来执行此操作。我得到的分数不包括最新的比赛,然后获得包括最新比赛的分数,并在我绘制桌子时进行比较。
示例:
以前的游戏结果:
SELECT p.name, p.id, SUM(g.points) AS score
FROM players p INNER JOIN games g ON p.id=g.player_id
WHERE g.id<5
ORDER BY score DESC
然后将它们存储在一个数组中:
$i=1;
while($row = mysql_fetch_assoc($results){
$prevPositions[$row['id']] = $i++;
//render row
}
所有游戏结果:
SELECT p.name, SUM(g.points) AS score
FROM players p INNER JOIN games g ON p.id=g.player_id
ORDER BY score DESC
然后在渲染表时解决差异:
$i=1;
while($row = mysql_fetch_assoc($results){
$change = $prevPositions[$row['id']] - $i++;
//render row
}
这样做很好 - 但如果我只使用一个陈述而不是两个陈述,我会感觉更好。
答案 0 :(得分:1)
试试这个:
SELECT (S0.Rank - S1.Rank) As Change, S1.Rank As Position, S1.name, S1.score
FROM (SELECT p.name, p.id, SUM(g.points) AS score, @rank1:=@rank1+1 As rank
FROM (SELECT @rank1:=0) r, players p
INNER JOIN games g ON p.id=g.player_id
ORDER BY score DESC) S1
JOIN
(SELECT p.id, SUM(g.points) AS score, @rank2:=@rank2+1 As rank
FROM (SELECT @rank2:=0) r, players p
INNER JOIN games g ON p.id=g.player_id
WHERE g.id<5
ORDER BY score DESC) S0
ON S0.id = s1.id
(我还没有测试过!)