开发者

What's the best way to query for position changes?

开发者 https://www.devze.com 2022-12-08 23:22 出处:网络
I have a table of results I\'d like to display: change | position | name | score | |----------------------------------|

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 开发者_JAVA技巧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!)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号