1)创建表tb1
SQL> create table tb1(id int,name varchar2(10));
表已创建。
SQL> insert into tb1(id) values(1);
已创建 1 行。
SQL> insert into tb1(id) values(2);
已创建 1 行。
SQL> insert into tb1(id) values(3);
已创建 1 行。
SQL> insert into tb1(id) values(10);
已创建 1 行。
SQL> commit;
提交完成。
2)创建表tb2
SQL> create table tb2(id int,name varchar2(10));
表已创建。
SQL> insert into tb2 values(1,'A');
已创建 1 行。
SQL> insert into tb2 values(2,'B');
已创建 1 行。
SQL> insert into tb2 values(3,'C');
已创建 1 行。
SQL> commit;
提交完成。
3)查看两张表数据
SQL> select * from tb1;
ID NAME
---------- ----------
1
2
3
10
SQL> select * from tb2;
ID NAME
---------- ----------
1 A
2 B
3 C
SQL> update tb1 t set t.name=select b.name from tb2 b where t.id=b.id; --错误写法
update tb1 t set t.name=select b.name from tb2 b where t.id=b.id
*
第 1 行出现错误:
ORA-00936: 缺失表达式
SQL> ed
已写入 file afiedt.buf
1 update tb1 t set t.name=(select b.name from tb2 b where t.id=b.id)
2* where exists(select *from tb2 b where t.id=b.id)
SQL> /
已更新3行。
4)更新后tb1表的内容:
SQL> select * from tb1;
ID NAME
---------- ----------
1 A
2 B
3 C
10
SQL> select * from tb2;
ID NAME
---------- ----------
1 A
2 B
3 C
5)如果tb2表id不唯一,更新会是什么情况?
SQL> insert into tb2 values(1,'D');
已创建 1 行。
SQL> commit;
提交完成。
SQL> select * from tb2;
ID NAME
---------- ----------
1 A
2 B
3 C
1 D
SQL> update tb1 t set t.name=(select b.name from tb2 b where t.id=b.id)
2 where exists(select *from tb2 b where t.id=b.id);
update tb1 t set t.name=(select b.name from tb2 b where t.id=b.id)
*
第 1 行出现错误:
ORA-01427: 单行子查询返回多个行
1. 对于子查询的值只能是一个唯一值,不能是多值。
2. 子查询在绝大多数情况下,最后面的where EXISTS子句是重要的,否则将得到错误的结果。
且where EXISTS子句可用另一方法代替,如上。最后的子句是对a表被更新记录的限制,如无此句,对于a表中某记录,如在b表中关联不到对应的记录,则该记录被更新字段将被更新为null。
where EXISTS子句就是排除对a表中该情况的记录进行更新。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26937943/viewspace-1192119/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/26937943/viewspace-1192119/