What's the best way to request position changes?
I have a table of results that I would like to display:
| change | position | name | score |
|----------------------------------|
| - | 1 | Bob | 10 |
| +1 | 2 | Tom | 8 |
| -1 | 3 | Sam | 7 |
|----------------------------------|
The change column reflects the movement of the person's position, so the transition from 3rd to 2nd is +1, and the transition from 2nd to 3rd is -1, etc. So in the example above, since Tom's last game overtook Sam.
Can I write a single SQL statement containing the results including the "change" column?
I am currently writing two queries for this. I get the scores excluding the last game and then I get the scores including the last game and compare when I draw the table.
Example:
Previous game:
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 store them 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 playing out the difference when rendering the table:
$i=1;
while($row = mysql_fetch_assoc($results){
$change = $prevPositions[$row['id']] - $i++;
//render row
}
This works great, but I'd be better off if I could use one statement instead of two.
source to share
Try the following:
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 have not tested!)
source to share