如何在一次 MySQL 数据库更新中执行多个数学方程式?
How to do multiple math equations in one MySQL database update?
我有一个 MySQL 数据库行,用于存储游戏的尝试次数和平均得分:
+-----+----------+-----------+
| uid | attempts | avg_score |
| 4 | 3 | 15 |
+-----+----------+-----------+
用户完成游戏后,我想更新这两个表以根据新的尝试计算出新的平均值。
我想:
相乘(尝试 * avg_score = 45)
将 trial_score 添加到总数 avg_score (avg_score(45) + trial_score(5) = 50)
除法(avg_score(45)+ trial_score(5)/尝试=尝试+ 1)
PHP mySQL 语句让我有点头疼。我将在下面展示我的尝试。
$sql=("UPDATE gamescore SET attempts = attempts + 1,avg_score = ((attempts * avg_score + ?) / (attempts = attempts + 1)) WHERE uid=?");
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii",$_POST['trial_score'],$_SESSION['uid']);
$stmt->execute();
失败..显然...我需要在这里更正什么?
谢谢!
您必须除以 (attempts + 1)
而不是 (attempts = attempts + 1)
。
还要先设置 avg_score
的值,然后再设置 attempts
,因为如果先设置 attempts
,那么设置 avg_score
MySql 值的表达式中的值将使用修改后的attempts
(你可以找到更多here):
UPDATE gamescore
SET avg_score = (attempts * avg_score + ?) / (attempts + 1),
attempts = attempts + 1
WHERE uid = ?;
我有一个 MySQL 数据库行,用于存储游戏的尝试次数和平均得分:
+-----+----------+-----------+
| uid | attempts | avg_score |
| 4 | 3 | 15 |
+-----+----------+-----------+
用户完成游戏后,我想更新这两个表以根据新的尝试计算出新的平均值。
我想:
相乘(尝试 * avg_score = 45)
将 trial_score 添加到总数 avg_score (avg_score(45) + trial_score(5) = 50)
除法(avg_score(45)+ trial_score(5)/尝试=尝试+ 1)
PHP mySQL 语句让我有点头疼。我将在下面展示我的尝试。
$sql=("UPDATE gamescore SET attempts = attempts + 1,avg_score = ((attempts * avg_score + ?) / (attempts = attempts + 1)) WHERE uid=?");
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii",$_POST['trial_score'],$_SESSION['uid']);
$stmt->execute();
失败..显然...我需要在这里更正什么? 谢谢!
您必须除以 (attempts + 1)
而不是 (attempts = attempts + 1)
。
还要先设置 avg_score
的值,然后再设置 attempts
,因为如果先设置 attempts
,那么设置 avg_score
MySql 值的表达式中的值将使用修改后的attempts
(你可以找到更多here):
UPDATE gamescore
SET avg_score = (attempts * avg_score + ?) / (attempts + 1),
attempts = attempts + 1
WHERE uid = ?;