简体   繁体   English

每次添加新行时更新列表

[英]Update a column table everytime a new row is added

I am using PHP to insert data into a DB. 我正在使用PHP将数据插入数据库。 I have a table called games and it's defined this way : 我有一张叫做游戏的桌子,它是这样定义的:

ID  |  Score  |  Rank

I want the rank column to be updated everytime a new row is added. 我希望每次添加新行时都会更新等级列。 Rank column have to sort Games by score. 排名列必须按分数对游戏进行排序。

For example : 例如 :

ID  |  Score  |  Rank
1   |    5    |   2
2   |    9    |   1

When I add a new row (ID=3, Score=15) my table will be like this : 当我添加新行(ID = 3,分数= 15)时,我的表将如下所示:

ID  |  Score  |  Rank
1   |    5    |   3
2   |    9    |   2
3   |   15    |   1

I have tried this in PHP but it dosen't seem to work : 我已经在PHP中尝试过了,但是似乎没有用:

try {
   $bdd->exec("INSERT INTO games(score) VALUES('$score')");
} catch (Exception $e) {
   die ($e->getMessage());
}

try {
       $bdd->exec("UPDATE games set rank=(SELECT @curRank := @curRank + 1 
       AS rank FROM games g, (SELECT @curRank := 0) r
       ORDER BY  score;)");
    } catch (Exception $e) {
       die ($e->getMessage());
    }

Any ideas how can this be done with PHP ? 有什么想法可以用PHP完成吗? Or is there a way to set the column value by default to be the rank of the scores ? 还是有一种方法可以将列值默认设置为分数的等级?

try {
   $bdd->exec("SET @pos := 0;
   UPDATE games SET rank= ( SELECT @pos := @pos + 1 ) ORDER BY score DESC;)");
} catch (Exception $e) {
   die ($e->getMessage());
}

This worked for me. 这对我有用。 Thanks anyway. 不管怎么说,还是要谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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