首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Bulk insert,update if on conflict (bulk upsert) on Postgres

Bulk insert,update if on conflict (bulk upsert) on Postgres
EN

Stack Overflow用户
提问于 2015-12-29 23:52:54
回答 1查看 31.7K关注 0票数 51

我正在编写一个数据挖掘程序,它批量插入用户数据。

当前的SQL只是一个普通的大容量插入:

代码语言:javascript
复制
insert into USERS(
    id, username, profile_picture)
select unnest(array['12345']),
    unnest(array['Peter']),
    unnest(array['someURL']),
on conflict (id) do nothing;

如果发生冲突,我该如何更新?我试过了:

代码语言:javascript
复制
...
    unnest(array['Peter']) as a,
    unnest(array['someURL']) as b,
on conflict (id) do 
update set
    username = a,
    profile_picture = b;

但是它抛出了There is a column named "a" in table "*SELECT*", but it cannot be referenced from this part of the query.错误。

编辑

USERS表非常简单:

代码语言:javascript
复制
create table USERS (
    id      text not null primary key,
    username    text,
    profile_picture text
);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-30 20:23:16

结果是一个名为excluded的特殊表包含要插入的行(尽管名称很奇怪)

代码语言:javascript
复制
insert into USERS(
    id, username, profile_picture)
select unnest(array['12345']),
    unnest(array['Peter']),
    unnest(array['someURL'])
on conflict (id) do 
update set
    username = excluded.username,
    profile_picture = excluded.profile_picture;

http://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT

ON

UPDATE中的SET和WHERE子句确实可以使用表名(或别名)访问现有行,并可以使用特殊的excluded ...

访问建议插入的行

票数 107
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34514457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档