将Oracle MERGE语句迁移到PostgreSQL UPSERT语句

时间:2013-10-16 05:10:21

标签: sql oracle postgresql upsert sql-merge

是否可以帮助我将以下Oracle MERGE语句转换为有效的UPSERT语句,以便在PostgreSQL 9.3数据库中使用?

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);

3 个答案:

答案 0 :(得分:3)

我认为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)

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

答案 1 :(得分: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);

答案 2 :(得分:0)

今天我跑了这个,读了这些文档,最后使用的东西非常类似于我的理解,文档现在为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级别工作,因此我暂时无法提供有意义的示例,稍后会对此进行审核。

如果我没弄错的话,工作完全正常。我觉得被迫创造了一个不在那里的主键,但实际上属于那里。