Postgresql upsert 查询

发布于 2024-12-03 09:44:24 字数 978 浏览 6 评论 0原文

可能的重复:
重复更新时插入 (postgresql)
无法从 postgres 中的 UPDATE RETURNING 子句中进行选择

帮助理解我语法错误。我尝试在以下位置进行 upsert 查询的实现 PosgreSql:

create table tbl( key  int, val int);

insert into tbl(key,val)
   select distinct(key), 0 from unnest('{0,1,2,3,4,5}'::int[]) as key
       where key not in (
         update tbl set val = 1
             where key = any('{0,1,2,3,4,5}'::int[])
         returning key
);

错误是:

ERROR:  syntax error at or near "tbl"
ROWS 6:  update tbl set val = 1
                  ^

********** Error **********

ERROR: syntax error at or near "tbl"
SQL state: 42601
Character: 167

但是更新子查询没有插入部分效果很好。

有没有最简单的方法来进行更新插入查询?

Possible Duplicate:
Insert, on duplicate update (postgresql)
Cannot SELECT from UPDATE RETURNING clause in postgres

Help to understand me syntax error. I try to make such implementation of upsert query in
PosgreSql:

create table tbl( key  int, val int);

insert into tbl(key,val)
   select distinct(key), 0 from unnest('{0,1,2,3,4,5}'::int[]) as key
       where key not in (
         update tbl set val = 1
             where key = any('{0,1,2,3,4,5}'::int[])
         returning key
);

error is :

ERROR:  syntax error at or near "tbl"
ROWS 6:  update tbl set val = 1
                  ^

********** Error **********

ERROR: syntax error at or near "tbl"
SQL state: 42601
Character: 167

But update subquery without insert part work well.

Is any easiest way to make upsert query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

彩虹直至黑白 2024-12-10 09:44:24

您的问题被建议为重复问题,因为 PostgreSQL 没有 UPSERT 命令的解决方案已经发布,它确实回答了您如何实现 UPSERT 的问题。

为了回答您的语法错误问题,您尝试做的事情目前是不可能的。您会发现在即将推出的 PostgreSQL 9.1 版本中可能会出现这种情况的变体,它将支持WITH子句中的数据修改语句:
http://www.postgresql.org/docs /9.1/static/queries-with.html#QUERIES-WITH-MODIFYING

Your question was suggested as a duplicate because a solution to PostgreSQL not having an UPSERT command was already posted, which does answer your question of how to implement UPSERT.

In answer to your syntax error question you are trying to do is not currently possible. You will find that a variation of it is possible in the upcoming version 9.1 of PostgreSQL, which will support data modifying statements in a WITH clause:
http://www.postgresql.org/docs/9.1/static/queries-with.html#QUERIES-WITH-MODIFYING

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文