[英]What's the best way to query for position changes?
I have a table of results I'd like to display: 我有一张要显示的结果表:
| change | position | name | score |
|----------------------------------|
| - | 1 | Bob | 10 |
| +1 | 2 | Tom | 8 |
| -1 | 3 | Sam | 7 |
|----------------------------------|
The change column reflects the position movement of the person, so moving from 3rd to 2nd is +1, and moving from 2nd to 3rd is -1 etc. So in the above example, since the last game Tom has overtaken Sam. 更改列反映了人的位置移动,因此从第三名到第二名的移动是+1,从第二名到第三名的移动是-1等。因此在上面的示例中,由于汤姆上一场超越了萨姆。
Can I write a single SQL statement that provides the results including the 'change' column? 我可以编写一条提供结果(包括“更改”列)的SQL语句吗?
Right now I'm writing two queries to do this. 现在,我正在编写两个查询来执行此操作。 I get the scores excluding the latest game, then get the scores including the latest game and compare when I draw the table.
我得到不包括最新游戏的分数,然后得到包含最新游戏的分数,并在我绘制表格时进行比较。
Example: 例:
Previous game results : 以前的游戏结果 :
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
Then storing these in an array: 然后将它们存储在数组中:
$i=1;
while($row = mysql_fetch_assoc($results){
$prevPositions[$row['id']] = $i++;
//render row
}
All game results : 所有游戏结果 :
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
And then working out the difference when rendering the table: 然后计算呈现表时的区别:
$i=1;
while($row = mysql_fetch_assoc($results){
$change = $prevPositions[$row['id']] - $i++;
//render row
}
This works fine - but I'd feel better if I could just use one statement rather than two. 这很好用-但是如果我只使用一个语句而不是两个语句,我会感觉更好。
Try this one: 试试这个:
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
(I haven't tested!) (我还没有测试!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.