Postgres 递增列中的空值

Postgres incrementing null value in a column

在 Postgres 9.3 中,当 table 中的字段具有空值时,以下表达式不起作用:

update table_statatistic set members = members + 1 WHERE user_id = ; 

然而,当字段具有整数值时,此查询将其递增 1 没有问题。

问题是:

  1. 为什么会这样。
  2. 如何解决。

您需要使用 coalesce 来检查空值

update table_statatistic set members = coalesce(members, 0) + 1 WHERE user_id = 

改用COALESCE()COALESCE 函数 returns 它的第一个参数不为空。仅当所有参数都为 null 时才返回 Null。它通常用于在检索数据以显示时用默认值替换空值

UPDATE table_statatistic SET members = COALESCE(members,0) + 1 WHERE user_id = ;