【问题标题】:update value only when value changed仅在值更改时更新值
【发布时间】:2021-04-21 21:08:31
【问题描述】:

我必须从另一个表更新 main_table 数据。以下是声明

我们将根据 type_key 在 value_string、value_date 中的任何一列中或为 key 获取 value。 (例如,如果 type_key 是字符串,那么 value_string 将具有值,而 value_date 为空)。有一个触发器可以确保这个约束。

update main_table t set
    value_string=value_string,
    value_date=value_date,
    value_int=value_int,
    updated_on=now(),
    status=status
from import_table imp where t.key=imp.key

即使 value_string 或 value_date 的值没有变化,updated_on 也会发生变化。我希望仅在值发生变化时更新 updated_on 。所以我将更新查询更改为以下

update main_table t set
    value_string=value_string,
    value_date=value_date,
    updated_on= (case when type_key='string' and t.value_string!=imp.value_string 
                    then now()
                 when type_key='date' and t.value_date!=imp.value_date 
                    then now()
                 when type_key='int' and t.value_int!=imp.value_int
                    then now()
                else updated_on end),
    status=status
from import_table imp where t.key=imp.key

是否有更好的方法来重写上述查询以提高查询的性能?

【问题讨论】:

    标签: sql postgresql sql-update insert-update


    【解决方案1】:

    我会添加一个 WHERE 条件,仅当至少有一个值不同时才会更改行。

    update main_table t 
     set
        value_string = imp.value_string,
        value_date = imp.value_date,
        value_int = imp.value_int,
        updated_on = now(),
        status = imp.status
    from import_table imp 
    where t.key = imp.key
      and (   t.value_string is distinct from imp.value_string
           or t.value_date is distinct from imp.value_date
           or t.value_int is distinct from imp.value_int
           or t.status is distinct from imp.status);
    

    或者你可以写成

    where t.key = imp.key
      and (t.value_string, t.value_date, t.value_int, t.status) 
          is distinct from (imp.value_string, imp.value_date, imp.value_int, imp.status);
    

    【讨论】:

      猜你喜欢
      • 2015-01-02
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 2017-12-06
      • 2020-05-26
      • 1970-01-01
      相关资源
      最近更新 更多