PostgreSQL Upsert (On Conflict) with same values in Insert and Update

扶醉桌前 提交于 2019-12-23 16:28:13

问题


Can I simplify the syntax when I use the same values in an Insert... On Conflict statment?

INSERT INTO cars 
  (car_id, car_type, car_model) 
values
  (1, 'tesla', 'model s')
ON CONFLICT (car_id) DO UPDATE SET 
  car_type = 'tesla',
  car_model = 'model s';

There are many more statements of this kind because they are part of a script that gets run on every application update.

Bascially I am looking for a way to not specify the same value twice.


回答1:


Use the excluded keyword:

INSERT INTO cars 
  (car_id, car_type, car_model) 
values
  (1, 'tesla', 'model s')
ON CONFLICT (car_id) DO UPDATE SET 
  car_type = excluded.car_type,
  car_model = excluded.car_model;

This also works correctly with multiple rows, e.g:

INSERT INTO cars 
  (car_id, car_type, car_model) 
values
  (1, 'tesla', 'model s'), 
  (2, 'toyota', 'prius')
ON CONFLICT (car_id) DO UPDATE SET 
  car_type = excluded.car_type,
  car_model = excluded.car_model;


来源:https://stackoverflow.com/questions/39892913/postgresql-upsert-on-conflict-with-same-values-in-insert-and-update

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