我必须从另一个表更新main_table数据。下面是语句
根据type_key,我们将在value_string、行中的value_date或关键字中的任何一列中都有值。(例如,如果type_key是字符串,则value_string将具有值,而value_date为null)。有一个触发器确保了这个约束。
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 query更改为以下内容
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
有没有更好的方法来重写上面的查询来提高查询性能?
发布于 2021-01-18 07:45:09
我将添加一个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);
https://stackoverflow.com/questions/65759785
复制