PostgreSQL部分索引和UPSERT
发布时间:2020-12-13 18:07:00  所属栏目:百科  来源:网络整理 
            导读:经过谷歌搜索后,我的问题描述如下: CREATE TABLE security ( id SERIAL PRIMARY KEY,vendor VARCHAR(20),external_id VARCHAR(20),extinct BOOLEAN DEFAULT FALSE);CREATE UNIQUE INDEX unique_vendor ON security(vendor,extinct) where vendor is not nul
                
                
                
            | 
                         
 经过谷歌搜索后,我的问题描述如下: 
  
  
  
CREATE TABLE security ( id SERIAL PRIMARY KEY,vendor VARCHAR(20),external_id VARCHAR(20),extinct BOOLEAN DEFAULT FALSE ); CREATE UNIQUE INDEX unique_vendor ON security(vendor,extinct) where vendor is not null; CREATE UNIQUE INDEX unique_external_id ON security(external_id,extinct) where external_id is not null; 试图插入值: insert into security (vendor,external_id,extinct) 
  values('Legion','LGNONE',false)
  ON CONFLICT(vendor,extinct) DO UPDATE
  SET vendor = 'Legion',external_id = 'LGNONE',extinct = false; 
 结果是: [42P10] ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification Altho这个工作(按规格): insert into security (vendor,extinct) 
    values('Legion',false)
    ON CONFLICT DO NOTHING; 
 PostgreSQL documentation stands that it should work PostgreSQL v9.5 我的目标是找到在多个可空列上在此表上创建唯一索引的方法,并在UPSERT上使用新行更新旧行 
 冲突中使用的 
                          conflict_target必须标识现有的唯一索引.你不能使用 
  
  
 on conflict (vendor,extinct) 因为三列上没有索引. Postgres结合多个索引以满足您的冲突目标并不是那么聪明. 但是,您可以像这样创建一个部分索引: create unique index unique_vendor_external_id 
    on security(vendor,extinct) 
    where coalesce(vendor,external_id) is not null; 
 现在您可以将这三列用作冲突目标: insert into security (vendor,false)
on conflict (vendor,extinct)          -- exact match to the index definition 
    where coalesce(vendor,external_id) is not null -- obligatory index_predicate
do update set
    vendor = excluded.vendor,external_id = excluded.external_id,extinct = excluded.extinct 
 注意排除使用特殊记录.对于文档: 
 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
相关内容
- ruby-on-rails – 在Rspec测试中使用Devise进行身份验证
 - ruby-on-rails – 如何使用带有Draper gem的i18n翻译方法?
 - PostgreSQL adminpack扩展的作用
 - c# – ASP.NET使用身份验证标头将JSON数据发布到HTTP API
 - cocos2dx 如何编译android 打包
 - Swift开发Sprite Kit游戏实践(四):背景音乐与Game Over
 - xcode – 无法推送最近提交给Github的已被推送到Bitbucket
 - Postgresql 插入数据时自动截取一定长度的字符串
 - VB遍历目录文件夹2
 - XML之DOM4J解析-总结四种方法
 
