【每日一练SQL】oracle的merge into函数的应用updateORinsert

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/debimeng/article/details/87886711

oracle的merge into函数的应用updateORinsert

SQL题:
如果表a里id没有在表b,则将数据插入表b,如表a里id在表b,则更新表b里的数据为表a的

解答:
简单的解释就是表a的数据如果不在表b则将表a的数据插入表b;
如果表a的数据在表b,则将表b的数据更新为表a的数据。

思路:
使用merge into函数,其主要的使用方法就是对两表进行操作
判断表中有没有符合on()条件中的数据,有了就更新数据,没有就插入数据。

例子:

create table test_a(tid int,tname varchar2(20),phone int);
create table test_b(tid int,tname varchar2(20),phone int);

insert into test_a values(1,'Lisi',123);
insert into test_a values(2,'Wangwu',321);
insert into test_a values(3,'Zhaoliu',1234456);

insert into test_b values(1,'aaa',111);
insert into test_b values(4,'BBB',222);

commit;

--test_a表
TID    TNAME    PHONE
1        Lisi            123
2        Wangwu    321
3        Zhaoliu     1234456

--test_b表
TID    TNAME    PHONE
1        aaa        111
4        BBB        222

--执行语句

merge into test_b b
using test_a a
on (b.tid = a.tid)
when matched then
  update set b.tname = a.tname, b.phone = a.phone
when not matched then
  insert (b.tid, b.tname, b.phone) values (a.tid, a.tname, a.phone);

commit;

--执行语句后的表b
TID    TNAME    PHONE
3    Zhaoliu       1234456
2    Wangwu     321
1    Lisi             123
4    BBB            222

猜你喜欢

转载自blog.csdn.net/debimeng/article/details/87886711