【发布时间】: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