PostgreSQL 10: With this upsert function, how to update only if column value is different?

拟墨画扇 提交于 2019-12-13 04:32:58

问题


I'm looking to update apr only if it's different, right now, it looks like it updates regardless if it's different or same:

   INSERT INTO live_mytable (id, loan_type, apr, term, oldestyear) 
   SELECT id, loan_type, apr, term, oldestyear
   FROM   imp_mytable 
   ON CONFLICT (id,loan_type,term,oldestyear) DO update
   set apr = excluded.apr;

How can this query be changed to only update if value is different?


回答1:


You can use a WHERE clause on the update:

 INSERT INTO live_mytable (id, loan_type, apr, term, oldestyear) 
   SELECT id, loan_type, apr, term, oldestyear
   FROM   imp_mytable 
 ON CONFLICT (id,loan_type,term,oldestyear) 
 DO update
   set apr = excluded.apr
 WHERE 
      live_mytable.apr IS DISTINCT FROM 
      EXCLUDED.apr;


来源:https://stackoverflow.com/questions/54932543/postgresql-10-with-this-upsert-function-how-to-update-only-if-column-value-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!