PostgreSQL實現Oracle merge into功能

合併MERGE語句是Oracle9i新增的語法,用來合併UPDATE和INSERT語句。通過MERGE語句,根據一張表或子查詢的連接條件對另外一張表進行查詢,連接條件匹配上的進行UPDATE,無法匹配的執行INSERT。這個語法僅需要一次全表掃描就完成了全部工作,執行效率要高於INSERT+UPDATE

with upsert as (
    update a
        set col1 = b.col1,col2 = b.col2
        from b t
        where a.id = t.id and a.code = t.code
        returning a.id,a.code
)
insert
into a
select *
from b t
where not exists(
        select 1
        from upsert b
        where t.id = b.id
          and t.code = b.code
    );

merge into A a using B b
on (a.id = b.id and a.code = b.code)
when matched then
update col1 = b.col1,col2 = b.col2
    when not matched then
insert
into a
values (b.col1, b.col2);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章