在插入和更新中具有相同值的PostgreSQL Upsert(冲突时) [英] PostgreSQL Upsert (On Conflict) with same values in Insert and Update

查看:323
本文介绍了在插入和更新中具有相同值的PostgreSQL Upsert(冲突时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

使用 已排除 关键字:

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;

这篇关于在插入和更新中具有相同值的PostgreSQL Upsert(冲突时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆