4

当我在 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';

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

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

4

1 回答 1

11

使用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;
于 2016-10-06T09:57:35.680 回答