现有两个表
表A:
order_id 客户姓名
1 林
2 张
3 程
4 王
5 陈
6 刘
表B:
order_id 客户姓名
1 null
2 null
3 null
4 null
5 null
我想把B表的 客户姓名 更新为与A表order_id相对应的的客户姓名,请教了!!
表A:
order_id 客户姓名
1 林
2 张
3 程
4 王
5 陈
6 刘
表B:
order_id 客户姓名
1 null
2 null
3 null
4 null
5 null
我想把B表的 客户姓名 更新为与A表order_id相对应的的客户姓名,请教了!!
where exists (select 1 from a where a.order_id=b.order_id)
(select 客户姓名 from a where a.order_id=b.order_id)
where exists (select 1 from a where a.order_id=b.order_id)
如果不加,则不存在的order_id其对应的字段将会被设置为NULL。
SQL> select * from test; DEPTNO DNAME LOC
---------- -------------- -------------
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
50 hk hkSQL> savepoint updatea;保存点已创建。SQL> update test set dname=
2 (select dname from scott.dept t where t.deptno=test.deptno);已更新5行。
--如果不加where exists ... 就会把50号部门的也更新,而且更新为null
SQL> select * from test; DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 hkSQL> rollback to updatea;重算已完成。SQL> select * from test; DEPTNO DNAME LOC
---------- -------------- -------------
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
50 hk hkSQL> update test set dname=
2 (select dname from scott.dept t where t.deptno=test.deptno)
3 where exists(select 1 from scott.dept t where test.deptno=t.deptno);已更新4行。SQL> commit;提交完成。
--加了where exists 后就不会更新50号部门,这样才是对的
SQL> select * from test; DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 hk hk
--发一个merge吧 Merge into tb a
using ta b
on (a.id=b.id)
when matched then update set a.客户名称=b.客户名称