仅在值更改时更新值

问题描述

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

我们将在一行中的 value_string,value_date 中的任何一列中都有值,或者对于一个键,基于 type_key。 (例如,如果 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,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

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

解决方法

我会添加一个 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);