我有一个表格来跟踪用户的每日得分。它看起来大致是这样的:
CREATE TABLE `DailyScores` (
`player_id` INTEGER NOT NULL,
`day_id` INTEGER NOT NULL,
`score` DOUBLE NOT NULL
);
我还有一个看起来像这样的玩家表:
CREATE TABLE `Players` (
`player_id` INTEGER NOT NULL,
`weighted_score` DOUBLE NOT NULL
);
现在,玩家 weighted_score 将每天从玩家历史数据中重新计算。我可以分几次执行此操作,如下所示:
-- Clear out the old values
UPDATE Players SET Players.weighted_score = 0;
-- Then several times with different @weight and @day values
UPDATE Players p JOIN DailyScores ds
ON p.player_id = ds.id
WHERE ds.day_id = @day
SET p.weighted_score = p.weighted_score + @weight * ds.score;
这处理了可能某天玩家没有得分条目的情况。
但是,我想将 UPDATE 重写为更像这样:
UPDATE Players p
JOIN DailyScores ds1 ON p.player_id = ds1.id
JOIN DailyScores ds2 ON p.player_id = ds2.id
JOIN DailyScores ds3 ON p.player_id = ds3.id
WHERE
ds1.day_id = @day1 AND
ds2.day_id = @day2 AND
ds3.day_id = @day3
SET p.weighted_score = @w1 * ds1.score + @w2 * ds2.score + @w3 * ds3.score;
但是我认为如果缺少分数,这将失败。有没有办法让缺失天数的值为 0?