进oracle项目组面试时问到了这个问题.
B表与A表表结构一样,无则插入有则更新如何用一条sql语句完成.
使用merge into.
例如有A和B俩个表,表结构如下:
ids varchar2(32),
names varchar2(32)
merge into A a --目标表
using B b --源表
on a.ids = b.ids --如果a表的a.ids和b表的b.ids一样,就读when matched then里的.
when matched then
update set a.names = b.names --注意此处不需要表名,自动把b插入到a.
when not matched then
insert (a.ids, a.names) values(b.ids, b.names) --注意此处语法,不需要into和表名.
关联子查询问题
select * from A a where exists(select * from B b where a.ids = b.ids)
注意这时是用外面A表的ids字段和里面B表的ids进行匹配.
假如A表有很多ids,那么此时sql执行器不知道用哪个ids好,所以会依次用a的每个ids与b.ids比较.
所以实际上运行了count(A表) + 1次sql语句.
请注意,这是关联子查询.