我试图做一个更新插入到具有表部分唯一索引PostgreSQL的部分唯一索引并更新插入
create table test (
p text not null,
q text,
r text,
txt text,
unique(p,q,r)
);
create unique index test_p_idx on test(p) where q is null and r is null;
create unique index test_pq_idx on test(p, q) where r IS NULL;
create unique index test_pr_idx on test(p, r) where q is NULL;
在平原而言,p
不为空,而只有一个q
或r
可以为null 。
重复插入扔约束违规预期
insert into test(p,q,r,txt) values ('p',null,null,'a'); -- violates test_p_idx
insert into test(p,q,r,txt) values ('p','q',null,'b'); -- violates test_pq_idx
insert into test(p,q,r,txt) values ('p',null, 'r','c'); -- violates test_pr_idx
然而,当我试图使用唯一约束为UPSERT
insert into test as u (p,q,r,txt) values ('p',null,'r','d')
on conflict (p, q, r) do update
set txt = excluded.txt
它仍然抛出约束违反
但我希望on conflict
子句t抓住它并做更新。
我在做什么错?我应该使用index_predicate
吗?
index_predicate Used to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. Follows CREATE INDEX format. https://www.postgresql.org/docs/9.5/static/sql-insert.html
https://stackoverflow.com/a/46728249/330315 –
的[部分索引可能的复制,同时执行了在Postgres一个UPSERT不使用关于冲突子句QL(https://stackoverflow.com/questions/46727740/partial-index-not-used-in-on-conflict-clause-while-performing-an-upsert-in-postg) – Eelke