2017-10-13 94 views
1

我试图做一个更新插入到具有表部分唯一索引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不为空,而只有一个qr可以为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

+0

https://stackoverflow.com/a/46728249/330315 –

+0

的[部分索引可能的复制,同时执行了在Postgres一个UPSERT不使用关于冲突子句QL(https://stackoverflow.com/questions/46727740/partial-index-not-used-in-on-conflict-clause-while-performing-an-upsert-in-postg) – Eelke

回答

2

我不认为这是可能使用多个部分索引作为冲突的目标。您应该尝试使用单个索引实现所需的行为。我能看到的唯一方式是使用在表达式唯一索引:

drop table if exists test; 
create table test (
    p text not null, 
    q text, 
    r text, 
    txt text 
); 

create unique index test_unique_idx on test (p, coalesce(q, ''), coalesce(r, '')); 

现在所有三个测试(执行两次)违反相同指数:

insert into test(p,q,r,txt) values ('p',null,null,'a'); -- violates test_unique_idx 
insert into test(p,q,r,txt) values ('p','q',null,'b'); -- violates test_unique_idx 
insert into test(p,q,r,txt) values ('p',null, 'r','c'); -- violates test_unique_idx 

在插入命令,你应该通过在索引定义中使用的表达式:

insert into test as u (p,q,r,txt) 
values ('p',null,'r','d') 
on conflict (p, coalesce(q, ''), coalesce(r, '')) do update 
set txt = excluded.txt;