简体   繁体   English

ON CONFLICT 中的 Postgresql 多列

[英]Postgresql multiple columns in ON CONFLICT

I want to only insert a row if every cell in that row is unique (excluding the id field of course) so I tried this如果该行中的每个单元格都是唯一的(当然不包括 id 字段),我只想插入一行所以我试过这个

INSERT INTO test (val, val2, val3) VALUES ('g', 'h', 'j') 
ON CONFLICT (val, val2, val3) DO NOTHING RETURNING id;

But turns out that this is invalid because the fields passed to ON CONFLICT must be constrained with UNIQUE .但事实证明这是无效的,因为传递给ON CONFLICT的字段必须受UNIQUE约束。 But I don't want that, I only want permutations of val, val2 and var3 to be unique, I don't want them to be unique individually.但我不希望那样,我只希望 val、val2 和 var3 的排列是唯一的,我不希望它们单独唯一。 And after the INSERT, no matter if it inserted or not I want to return the id field.在插入之后,无论是否插入,我都想返回 id 字段。 How may I do this?我该怎么做?

I solved this by creating the UNIQUE like this:我通过像这样创建 UNIQUE 解决了这个问题:

CREATE TABLE test (
  id SERIAL,
  val varchar(100),
  val2 varchar(100),
  val3 varchar(100),
  UNIQUE (val, val2, val3)
);

and then inserting like this:然后像这样插入:

INSERT INTO test (val, val2, val3) VALUES ('a', 'b', 'c') ON CONFLICT (val, val2, val3) DO UPDATE SET val='a' RETURNING id;

even if there is nothing to update, it makes it return the id即使没有任何更新,它也会返回id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM