首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Postgres Insert Insert On conflict update

Postgres Insert Insert On conflict update
EN

Stack Overflow用户
提问于 2016-11-20 02:09:06
回答 1查看 1.7K关注 0票数 2

我想使用on conflict do update-feature将数据从一个表("tmp")插入到另一个表("tbla")中。我的代码:

代码语言:javascript
复制
INSERT INTO tbla (id, col1, col2, col3) 
SELECT id, col1, col2, col3 FROM tmp

ON CONFLICT on constraint pkey_tbla DO UPDATE SET col1=tmp.col1 FROM tmp;

DROP TABLE tmp;

这段代码在"FROM tmp;“上返回了一个语法错误,如果没有FROM,就会出现错误:缺少表"tmp”的FROM-子句条目。有什么建议吗?

DB-Server在装有postgres 9.5的windows 7机器上的localhost上运行

EN

回答 1

Stack Overflow用户

发布于 2016-11-20 02:34:57

Documentation“请注意,特殊的排除表用于引用最初建议插入的值”https://www.postgresql.org/docs/9.5/static/sql-insert.html

修复:... DO UPDATE SET col1=EXCLUDED.col1;

代码语言:javascript
复制
x=> select * from tbla;
 id | col1 
----+------
  1 |    2
  2 |    3
(2 rows)

x=> truncate tmp;
TRUNCATE TABLE
x=> insert into tmp(id,col1) values (1,42);
INSERT 0 1
x=> INSERT INTO tbla(id,col1) SELECT id,col1 FROM tmp -- wrap line
    ON CONFLICT (id) DO UPDATE SET col1=EXCLUDED.col1;

INSERT 0 1
sh161119=> select * from tbla;
 id | col1 
----+------
  2 |    3
  1 |   42
(2 rows)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40696275

复制
相关文章

相似问题

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