4

您能帮我将以下 Oracle语句转换为在 PostgreSQL 9.3 数据库中使用MERGE的有效语句吗?UPSERT

MERGE INTO my_table a
     USING (SELECT v_c1 key,
                   v_c2 AS pkey,
                   v_c3 AS wcount,
                   v_c4 AS dcount
              FROM DUAL) b
        ON (    a.key = b.key
            AND a.pkey = b.pkey
WHEN MATCHED
THEN
   UPDATE SET wcount = b.wcount,
              dcount = b.dcount
WHEN NOT MATCHED
THEN
   INSERT     (key,
               pkey,
               wcount,
               dcount)
    VALUES(b.key,b.pkey,b.wcount,b.dcount);
4

3 回答 3

4

我认为 PostgreSQL 9.3 中没有 UPSERT 语句,但你可以这样做:

with cte_dual as (
    select
        v_c1 as key,
        v_c2 as pkey,
        v_c3 as wcount,
        v_c4 as dcount
), cte_update as (
    update my_table as a set
        wcount = b.wcount,
        dcount = b.dcount
    from cte_dual as b
    where b.key = a.key and b.pkey = a.pkey
    returning *
)
insert into my_table (key, pkey, wcount, dcount)
select d.key, d.pkey, d.wcount, d.dcount
from cte_dual as d
where not exists (select * from cte_update as u WHERE u.key = d.key and u.pkey = d.pkey)

您可以阅读几个类似的问题:

于 2013-10-16T08:06:54.303 回答
1

我今天跑了这个,阅读了这些文档,最终使用了与我理解文档现在建议的内容非常相似的东西UPSERT

INSERT INTO table (
    $INSERT_COLUMN_NAMES
)
VALUES (
    $INSERT_COLUMN_VALUES
)
ON CONFLICT (
    $LIST_OF_PRIMARY_KEY_COLUMN_NAMES
)
DO UPDATE SET
    $UPDATE_SET_SUBCLAUSE
WHERE 
    $WHERE_CONDITION_ON_PRIMARY_KEYS
;

我实际上是在 DAO 级别上工作的,所以目前我无法提供一个有意义的例子,稍后会回顾一下。

如果我没记错的话,它工作得很好。我觉得被迫创建一个不存在但实际上属于那里的主键。

于 2017-10-16T16:59:27.653 回答
0

upsert 在 Postgres 9.3 中工作,

例子-

WITH upsert as
 (update mytable2 m set sales=m.sales+d.sales, status=d.status from mytable d where m.pid=d.pid
 RETURNING m.*
)
insert into mytable2 select a.pid, a.sales,'NEW' from mytable a where a.pid not in (select b.pid from mytable2 b);
于 2015-07-27T05:59:04.067 回答