【问题标题】:MYSQL Update using SUM the same tableMYSQL 使用 SUM 更新同一张表
【发布时间】:2020-12-22 01:14:28
【问题描述】:

您好,很抱歉,我知道这只是基本的。仅在同一张表上使用 sum 进行简单更新。我需要得到

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))

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

【问题讨论】:

    标签: mysql sql sum calculated-columns


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      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
      

      附加的列为您提供始终最新的数据透视图。您甚至可以根据自己的喜好对其进行索引,以便高效查询。

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

      【讨论】: