如何在一个查询中插入和更新

i2byvkas  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(306)

正在尝试在查询中写入insert和update。因此,我的方案是-如果存在一行,则向上插入并插入新行。但行不存在,只能插入。
所以我想说的是-

Select exist(Select 1 from table where condition)

if(exists){

Update table set column =value where condition.
Insert into table (column) values (" ").

}else{

Insert into table (column) values (" ")

}

由于我在这里写了这么多的查询,有没有可能我可以涵盖所有这些在一个查询。
提前谢谢

dphi5xsq

dphi5xsq1#

只需插入查询并检查 CONFLICT 条款。
postgresql支持conflict子句,该子句在某个特定事件发生冲突时触发 CONSTRAINT .
假设你有一张table t 带主键列 id 以及 name 字段:

CREATE TABLE t ( id integer primary key, name varchar(255));

插入时,可以检查主键约束:

INSERT INTO t (id, name) VALUES (1, 'Name1')
ON CONFLICT ON t_id_constraint
DO UPDATE SET name='Name1';
``` `t_id_constraint` 是id列唯一性的约束名称。当不存在冲突时,此查询将向表中插入新值,并在表中找到新id时更新。
原始答案

相关问题