我有一个像这样的mysql表:
CREATE TABLE IF NOT EXISTS `entries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`domain_name` varchar(255) NOT NULL,
`presentation_name` varchar(255) NOT NULL,
`total_score` mediumint(9) NOT NULL,
`times_played` mediumint(9) NOT NULL,
`avg_score` float(4,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=206 ;
我正在用PHP更新数据 但查询计算错误的' avg_score'在更新时。可以说,整行看起来像这样:
id domain_name presentation_name total_score times_played avg_score
1 test.com test 30 3 10.00
但是当我使用新数据运行此更新查询时:
$score = 6;
$query = "UPDATE `entries`
SET
total_score = (total_score + $score),
times_played = (times_played + 1),
avg_score = ( (total_score + $score) / (times_played + 1) )
WHERE id = '1'";
它变成这样:
id domain_name presentation_name total_score times_played avg_score
1 test.com test 36 4 8.40
你可以看到' avg_score'是错的(应该是9.00)。我在phpmyadmin中尝试了相同的查询并得到了相同的错误计算。我真的无法在这里找到我做错的事。
答案 0 :(得分:2)
见
total_score = (total_score + $score),
36 = 30 + 6
times_played = (times_played + 1),
4 = 3 + 1
然后你做
avg_score = ( (total_score + $score) / (times_played + 1) )
8.4 =(36 + 6)/ 5
是对的!
答案 1 :(得分:2)
来自MySQL manual:
以下语句中的第二个赋值将col2设置为 当前(更新)col1值,而不是原始col1值。结果 是col1和col2具有相同的值。 此行为不同于 标准SQL 。
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
因此,您可以在更新平均值时省略+分数和+ 1:
UPDATE `entries` SET
total_score = total_score + $score,
times_played = times_played + 1,
avg_score = total_score / times_played
WHERE id = '1'
答案 2 :(得分:1)
看起来您的前两列已更新,更新第三列时会使用更新的值,请注意8.4 = (36 + 6) / (4 + 1)
因此,您不需要第+1
和+ $score
作为第三列。
虽然你真的不应该在数据库中存储重复的数据,因为这只会导致这样的问题。
只需在php或mysql中计算您需要的平均值。
答案 3 :(得分:1)
尝试: 改变顺序(首选方法)
SET
avg_score = ( (total_score + $score) / (times_played + 1) ) ,
total_score = (total_score + $score),
times_played = (times_played + 1)
或:
SET
total_score = (total_score + $score),
times_played = (times_played + 1),
avg_score = ( (total_score) / (times_played) )
您正在引用已在后续计算中调整的字段,但假设它们保持不变。
答案 4 :(得分:0)
看起来这些更新正在逐步完成。
即,总得分为36,次数达到4,然后avg_score的计算完成(36 + 6,4 + 1)= 42/5 = 8.4
尝试用另一句话更新avg_score。
不知道这是做什么的。
答案 5 :(得分:0)
更改:强>
$score = 6;
$query = "UPDATE `entries`
SET
total_score = (total_score + $score),
times_played = (times_played + 1),
avg_score = ( (total_score + $score) / (times_played + 1) )
WHERE id = '1'";
要强>
$score = 6;
$query = "UPDATE `entries`
SET
total_score = (total_score + $score),
times_played = (times_played + 1),
avg_score = (total_score /times_played )
WHERE id = '1'";