【问题标题】:Postgresql Batch insert and on conflict batch updatePostgresql 批量插入和冲突批量更新
【发布时间】:2017-09-15 15:44:05
【问题描述】:

我正在尝试将行批量插入到 postgres 数据库中,并在冲突时更新冲突的行。我想知道最好的方法是什么。我目前的查询无法插入任何行,但如果我删除 on 冲突,它会完美运行。我也没有收到任何错误。

这是我正在使用的当前查询: 'INSERT INTO table (x1, x2, x3, ...) VALUES %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,... ON CONFLICT DO UPDATE SET (x4, x5, x6) = %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,...'

我有一个函数用 (x1, x2, ...) 形式的元组填充 %s 值

我的桌子是这样的 Table "public.table" Column | Type | Modifiers
--------------+---------+----------------------------------------------- id | integer | not null default nextval('table_id_seq'::regclass) x1 | text | not null x2 | text | not null x3 | integer | not null x4 | text | not null x5 | text | not null x6 | text | not null Indexes: "table_feature_pkey" PRIMARY KEY, btree (id)

提前致谢。如果您需要更多信息,请告诉我。

【问题讨论】:

  • 不太明白这与批处理文件有什么关系?在您的问题中没有看到任何批处理文件代码。

标签: sql postgresql


【解决方案1】:

1.插入前

2.命令

3.插入后

【讨论】:

  • EXCLUDED 是这里的关键字。
【解决方案2】:

您将使用明显不正确的语法。有桌子

create table a_table(id serial primary key, x1 int, x2 int);

psql

中试试这个
insert into a_table (x1, x2) 
values (1,2), (3,4)
on conflict do
update set (x1, x2) = (1,2), (3,4);

得到

ERROR:  syntax error at or near "3"
LINE 4:  update set (x1, x2) = (1,2), (3,4);

另一方面,ON CONFLICT 在这种情况下毫无意义。永远不会发生冲突,因为使用的列(或列组)都不是唯一的。

查看INSERT syntax,了解更多关于UPSERT in wiki的信息。

【讨论】:

  • 那么如果说 x1 和 x2 列是唯一的呢?我是否必须在创建表时以某种方式指定它,然后执行“on conflict (x1, x2) do update”之类的操作?
  • 实际上在插入多行时(假设列或列组是唯一的),合理的方法是on conflict ... do nothing,因为update 不能多次影响同一行(就像许多插入一样可能发生)。
猜你喜欢
  • 1970-01-01
  • 2012-03-19
  • 2016-04-03
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多