如何正确地在postgres 9.5

时间:2016-04-22 16:35:26

标签: sql postgresql upsert postgresql-9.5

使用postgresql 9.5正确语法upsert,下面的查询显示column reference "gallery_id" is ambiguous错误,为什么?

var dbQuery = `INSERT INTO category_gallery (
  category_id, gallery_id, create_date, create_by_user_id
  ) VALUES ($1, $2, $3, $4)
  ON CONFLICT (category_id)
  DO UPDATE SET
  category_id = $1,
  last_modified_date = $3,
  last_modified_by_user_id = $4
  WHERE gallery_id = $2`;

我尝试将WHERE gallery_id = $2;更改为WHERE category_gallery.gallery_id = $2;,然后显示错误there is no unique or exclusion constraint matching the ON CONFLICT specification,但是我不想将gallery_id或category_id设置为唯一,因为我我想确保两列相同然后更新....

如何在postgres 9.5中正确进行upsert?

如果ON CONFLICT需要唯一列,我应该使用其他方法,如何?



我想确保多列冲突然后更新,什么是正确的用法

var dbQuery = `INSERT INTO category_gallery (
  category_id, gallery_id, create_date, create_by_user_id
  ) VALUES ($1, $2, $3, $4)
  ON CONFLICT (category_id, gallery_id)
  DO UPDATE SET
  category_id = $1,
  last_modified_date = $3,
  last_modified_by_user_id = $4
  WHERE gallery_id = $2`;


var dbQuery = `INSERT INTO category_gallery (
  category_id, gallery_id, create_date, create_by_user_id
  ) VALUES ($1, $2, $3, $4)
  ON CONFLICT (category_id AND gallery_id)
  DO UPDATE SET
  category_id = $1,
  last_modified_date = $3,
  last_modified_by_user_id = $4
  WHERE gallery_id = $2`;

table(category_id,gallery_id不是唯一列)

category_id | gallery_id | create_date | create_by_user_id | last_modified_date | last_modified_by_user_id
1 | 1 | ...  
1 | 2 | ...
2 | 2 | ...
1 | 3 | ...

2 个答案:

答案 0 :(得分:46)

ON CONFLICT构造需要UNIQUE约束才能工作。来自INSERT .. ON CONFLICT clause的文档:

  

可选的ON CONFLICT子句指定了引发唯一违规排除约束违规错误的替代操作。对于建议插入的每个单独的行,插入继续进行,或者,如果违反了conflict_target指定的仲裁器约束或索引,则采用替代的conflict_action。 ON CONFLICT DO NOTHING只是避免插入行作为替代操作。 ON CONFLICT DO UPDATE更新与建议插入的行冲突的现有行作为替代操作。

现在,问题不是很清楚,但您可能需要对2列合并UNIQUE约束:(category_id, gallery_id)

ALTER TABLE category_gallery
    ADD CONSTRAINT category_gallery_uq
    UNIQUE (category_id, gallery_id) ;

如果要插入的行与表格中已有行的两个值相匹配,那么请执行INSERT

而不是UPDATE
INSERT INTO category_gallery (
  category_id, gallery_id, create_date, create_by_user_id
  ) VALUES ($1, $2, $3, $4)
  ON CONFLICT (category_id, gallery_id)
  DO UPDATE SET
    last_modified_date = EXCLUDED.create_date,
    last_modified_by_user_id = EXCLUDED.create_by_user_id ;

您可以使用UNIQUE约束的列:

  ON CONFLICT (category_id, gallery_id) 

或约束名称:

  ON CONFLICT ON CONSTRAINT category_gallery_uq  

答案 1 :(得分:4)

作为the currently accepted answer的简化替代,可以在创建表时匿名添加compare约束:

compare

然后,upsert查询变为(类似于已经回答的内容):

UNIQUE