简体   繁体   中英

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.

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.

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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM