PostgreSQL Upsert(冲突时)在插入和更新中具有相同的值

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

当我在 Insert...On Conflict 语句中使用相同的值时,我可以简化语法吗?

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';

还有更多此类语句,因为它们是在每次应用程序更新时获取 运行 的脚本的一部分。

基本上我正在寻找一种不指定相同值两次的方法。

使用excluded关键字:

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;

这也适用于多行,例如:

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;