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.
Can I write a single SQL statement that provides the results including the 'change' column?
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.