一道面试题,用一句SQL语句完成,请大家帮忙解决
假设有A,B 两张表,结构相同,但数据不同,现在需要将表B中的数据同步到表A 中,即B中存在的数据在A中不存在,
则直接插入到A中,如果两张表中都存在,刚将B中的数据更新到A中,假设两表的结构为(ColA NUMBER PRIMARY KEY, ColB VARCHAR2(30)), 请写一个SQL语句实现
------解决方案--------------------merge into
------解决方案----------------------语法
MERGE INTO table_name alias1
USING (table|view|sub_query) alias2
ON (join condition)
WHEN MATCHED THEN
UPDATE table_name
SET col1 = col_val1,
col2 = col2_val
WHEN NOT MATCHED THEN
INSERT (column_list) VALUES (column_values);
--实例 在一个同时存在Insert和Update语法的Merge语句中,总共Insert/Update的记录数,就是Using语句中alias2的记录数。
MERGE INTO T T1
USING (SELECT '1001' AS a,2 AS b FROM dual) T2
ON ( T1.a=T2.a)
WHEN MATCHED THEN
UPDATE SET T1.b = T2.b
WHEN NOT MATCHED THEN
INSERT (a,b) VALUES(T2.a,T2.b);
------解决方案--------------------楼上正解
------解决方案--------------------SQL code
create table TblA(ColA NUMBER PRIMARY KEY, ColB VARCHAR2(30));
create table TblB(ColA NUMBER PRIMARY KEY, ColB VARCHAR2(30));
insert into TblA
select * from TblB b where b.cola not in(select a.cola from TblA a group by a.cola)
update TblA a Set (a.ColB) =(select b.Colb from TblB b where a.cola=b.cola)