Merge Into 語法支援
阿新 • • 發佈:2021-10-28
KINGBASE 相容Oracle 語法,實現了merge into 的功能。以下以例子的形式,介紹merge into語法的使用。以下例子在V8R6 ,且 database_mode=oracle 環境下驗證過,database_mode=pg 不支援merge into 語法。
一、建立測試資料
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
create table source_table(s_id integer ,s_name char (9));
create table target_table(t_id integer ,t_name char (9));
insert into source_table values (1, 's_a' ),(2, 's_b' );
insert into target_table values (1, 't_a' ),(3, 't_c' );
test=# select * from source_table ;
s_id | s_name
------+-----------
1 | s_a
2 | s_b
(2 rows )
test=# select * from target_table ;
t_id | t_name
------+-----------
1 | t_a
3 | t_c
(2 rows )
|
二、測試例子
1、例子1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
test=# begin ;
BEGIN
test=# merge into target_table as t
test-# using source_table as s
test-# on (t.t_id=s.s_id)
test-# when matched then update set t.t_name=s.s_name
test-# when not matched then insert values (s.s_id,s.s_name);
MERGE 2
test=# select * from target_table order by t_id;
t_id | t_name
------+-----------
1 | s_a
2 | s_b
3 | t_c
(3 rows )
test=# rollback ;
ROLLBACK
|
注意:更新的列不能是ON 條件中被引用的列。
2、例子2
更新時可以通過WHERE 條件指明要更新的行,條件中既可以包含源表的列,也可以包含目標表的列,當指明WHERE 條件且條件為假時,則不更新。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
test=# begin ;
BEGIN
test=# merge into target_table as t
test-# using source_table as s
test-# on (t.t_id=s.s_id)
test-# when matched then update set t.t_name=s.s_name where t.t_id=3
test-# when not matched then insert values (s.s_id,s.s_name);
MERGE 1
test=#
test=# select * from target_table order by t_id;
t_id | t_name
------+-----------
1 | t_a --沒有被更新
2 | s_b
3 | t_c
(3 rows )
test=# rollback ;
ROLLBACK
|
3、例子3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
test=# begin ;
BEGIN
test=# merge into target_table as t
test-# using source_table as s
test-# on (t.t_id=s.s_id)
test-# when matched then update set t.t_name=s.s_name
test-# delete where t.t_name= 's_a'
test-# when not matched then insert values (s.s_id,s.s_name);
MERGE 3
test=# select * from target_table order by t_id;
t_id | t_name
------+-----------
2 | s_b
3 | t_c
(2 rows )
test=# rollback ;
ROLLBACK
|
DELETE 子句只刪除目標表和源表的ON 條件為真、並且是更新後的符合刪除條件的記錄,DELETE 子句不影響INSERT 項插入的行
三、Postgresql 實現類 merge into 的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
test=# begin ;
BEGIN
test=# with upsert as (
test(# update target_table
test(# set t_name = source_table.s_name
test(# from source_table
test(# where target_table.t_id = source_table.s_id
test(# returning target_table.*
test(# )
test-# insert into target_table select * from source_table
test-# where not exists (
test(# select 1
test(# from upsert b
test(# where source_table.s_id = b.t_id
test(# );
INSERT 0 1
test=# select * from target_table order by t_id;
t_id | t_name
------+-----------
1 | s_a
2 | s_b
3 | t_c
(3 rows )
test=# rollback ;
ROLLBACK
|