在同一个表上使用百分比计算进行更新

时间:2010-12-14 10:09:48

标签: mysql sql sql-update mysql-error-1093

我有一张这样的表:

ItemID      PersonID  Score      Percentage
==========================================
1             1       10         [ = 10 / 10+30 = 25%]
1             2       30         [ = 30 / 10+30 = 75%]
2             1       20         [ = 20 / 20+40 = 33%]
2             2       40         [ = 40 / 20+40 = 67%]

未输入“百分比”数据,但会在特定时间间隔自动计算。 计算结果为百分比=得分/项目ID总分

我没有使用“SELECT-do the maths-UPDATE”方法,而是尝试编写单个SQL来更新“Percentage”。

我尝试的是这样的:

UPDATE tb_temp AS t1 
    SET t1.Percentage = 
        CEIL( t1.Score / 
            (SELECT SUM(t2.Score) FROM tb_temp AS t2 WHERE t2.ItemID = t1.ItemID)
        );

但它不起作用。(错误代码:1093您不能在FROM子句中为更新指定目标表't1')。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

UPDATE tb_temp AS t1 
    SET t1.Percentage = 
        CEIL( t1.Score / 
            (SELECT SUM(t2.Score) FROM tb_temp AS t2 left join tb_temp AS t3 on t2.ItemID = t3.ItemID)
        );

答案 1 :(得分:-1)

尝试:

  UPDATE tb_temp t1 
     JOIN (SELECT ItemId, SUM(t2.Score) TotalScore
           FROM tb_temp 
           group by ItemId) t2 ON t2.ItemID = t1.ItemID
  SET t1.Percentage = CEIL( t1.Score / t2.TotalScore)