假设有以下2张源表A和表B
A(pkey,a1,a2,a3)
B(pkey.b1,b2,b3)
与此同时数据库里也有了一张目标表C,C的表结构为
C(pkey,a1,b1,c1,a2,b2)
把A和B中对应字段的数据同步到C中,同时c1的数据给个默认值:建表语句如下:
drop table A;
drop table B;
drop table C;
create table A(
pkey varchar2(10),
a1 varchar2(10),
a2 varchar2(10),
a3 varchar2(10),
PRIMARY KEY (pkey)
);
create table B(
pkey varchar2(10),
b1 varchar2(10),
b2 varchar2(10),
b3 varchar2(10),
PRIMARY KEY (pkey)
);
create table C(
pkey varchar2(10),
a1 varchar2(10),
b1 varchar2(10),
c1 varchar2(10),
a2 varchar2(10),
b2 varchar2(10),
PRIMARY KEY (pkey)
);
INSERT INTO A (pkey,a1,a2,a3) VALUES(1,'a','a','a');
INSERT INTO A (pkey,a1,a2,a3) VALUES(2,'a1','a1','a1');
INSERT INTO A (pkey,a1,a2,a3) VALUES(3,'a3','a3','a3');
INSERT INTO A (pkey,a1,a2,a3) VALUES(4,'a4','a4','a4');
INSERT INTO B (pkey,b1,b2,b3) VALUES(1,'b','b','b');
INSERT INTO B (pkey,b1,b2,b3) VALUES(2,'b1','b1','b1');
INSERT INTO B (pkey,b1,b2,b3) VALUES(3,'b2','b2','b2');
Merge into 为:
MERGE INTO C tmpC
USING (
SELECT
tmpA.pkey,
tmpA.a1,
tmpB.b1,
'c1的默认值',
tmpA.a2,
tmpB.b2
FROM
( SELECT pkey, a1, a2 FROM A )tmpA ,
( SELECT pkey, b1, b2 FROM B )tmpB
WHERE tmpB.pkey = tmpA.pkey
)tmp ON(tmpC.pkey=tmp.pkey)
WHEN MATCHED THEN
UPDATE SET
tmpC.a1=tmp.a1,
tmpC.b1=tmp.b1,
tmpC.c1='c1的默认值',
tmpC.a2=tmp.a2,
tmpC.b2=tmp.b2
WHEN NOT MATCHED THEN
INSERT (pkey,a1, b1,c1,a2,b2)VALUES(tmp.pkey,tmp.a1,tmp.b1,'c1的默认值',tmp.a2,tmp.b2);
若以A的主键Pkey为主,使用左连接
MERGE INTO C tmpC
USING (
SELECT
tmpA.pkey,
tmpA.a1,
tmpB.b1,
'c1的默认值',
tmpA.a2,
tmpB.b2
FROM
( SELECT pkey, a1, a2 FROM A )tmpA left join ( SELECT pkey, b1, b2 FROM B )tmpB on tmpB.pkey = tmpA.pkey
)tmp ON(tmpC.pkey=tmp.pkey)
WHEN MATCHED THEN
UPDATE SET
tmpC.a1=tmp.a1,
tmpC.b1=tmp.b1,
tmpC.c1='c1的默认值',
tmpC.a2=tmp.a2,
tmpC.b2=tmp.b2
WHEN NOT MATCHED THEN
INSERT (pkey,a1, b1,c1,a2,b2)VALUES(tmp.pkey,tmp.a1,tmp.b1,'c1的默认值',tmp.a2,tmp.b2);
在Mysql中的相同语句为:
INSERT REPLACE INTO C ( pkey, a1, b1, c1, a2, b2 )
VALUES
(
SELECT
tmp_A.pkey,
tmp_A.a1,
tmp_B.b1,
'c1的默认值',
tmp_A.a2,
tmp_B.b2,
FROM
( SELECT pkey, a1, a2 FROM A ) tmp_A,
( SELECT pkey, b1, b2 FROM B ) tmp_B
WHERE
tmp_B.pkey = tmp_A.pkey
);