MYSQL 使用相同的 SUM 更新 table

MYSQL Update using SUM the same table

您好,很抱歉,我只知道一些基础知识。仅使用相同 table 上的总和进行简单更新。我需要得到

total_tbl 
+-- month1 --- month2 --- month3 --- total --+ 
|     3          3          5                |
|     5          3          5                |
|     3                     4                |
|                5          5                |
+--------------------------------------------+

我需要使用 SUM 更新总计列。

到目前为止我有这个声明:

UPDATE total_tbl SET total = (SELECT SUM(month1,month2,month3))

即使一列没有值,我也应该更新。谢谢!

SUM() 用于对多行的表达式求和,通常使用 GROUP BY。如果要在同一行中添加表达式,只需使用普通加法即可。

使用 COALESCE() 为空列提供默认值。

UPDATE total_tbl
SET total = COALESCE(month1, 0) + COALESCE(month2, 0) + COALESCE(month3, 0)

您不需要存储此派生信息。我会推荐一个计算列:

alter table total_tbl
    add column total int -- or the datatype you need
    generated always as (coalesce(month1, 0) + coalesce(month2, 0) + coalesce(month3, 0)) stored

附加列让您始终了解最新的数据。您甚至可以根据需要对其进行索引,以便高效查询。

另一方面,手动维护值需要在每次行中的值更改时更新该列,这可能会很乏味。