一、业务场景:
(1)主从两个表,主表Student,有字段id、name、sex,从表Boy,有字段id、name,主从表同一对象id相同
(2)从表Boy的name属性被业务修改,定时批量处理主表,以维持主表name属性与从表一致
二、表结构
1、主表 Student
2、从表 Boy
三、建表SQL(DDL)
1、主表 Student
1 -- DDL
2 CREATE TABLE student (
3 id NUMBER NOT NULL ,
4 name VARCHAR2(255 BYTE) NULL ,
5 sex VARCHAR2(255 BYTE) NULL
6 )
7
8 ALTER TABLE student ADD CHECK (id IS NOT NULL);
9
10 -- DML
11 INSERT INTO student VALUES (‘1‘, ‘zhangsan‘, ‘boy‘);
12 INSERT INTO student VALUES (‘2‘, ‘lisi‘, ‘girl‘);
13 INSERT INTO student VALUES (‘3‘, ‘wangwu‘, ‘boy‘);
2、从表 Boy
1 -- DDL
2 CREATE TABLE boy (
3 id NUMBER NOT NULL ,
4 name VARCHAR2(255 BYTE) NULL
5 )
6
7 -- DML
8 INSERT INTO boy VALUES (‘1‘, ‘张三‘);
9 INSERT INTO boy VALUES (‘3‘, ‘王五‘);
四、DML
1、基本语法
1 -- DML
2 UPDATE student s SET s.name = ‘张三‘ WHERE id = 1;
2、变相
1 -- DML,0.015s
2 UPDATE student s
3 SET s.name = (
4 SELECT b.name FROM boy b WHERE s.id = b.id AND s.name != b.name
5 )
6 WHERE EXISTS (
7 SELECT 1 FROM boy b WHERE s.id = b.id AND s.name != b.name
8 );
9
3、快速游标法
1 -- DML,0.014s
2 BEGIN
3 FOR cur IN (
4 SELECT s.id sid, b.name bname
5 FROM student s, boy b
6 WHERE s.id = b.id AND s.name != b.name AND s.sex = ‘boy‘
7 ) loop
8
9 UPDATE student s SET s.name = cur.bname WHERE s.id = cur.sid;
10
11 END loop ;
12 END ;
13
4、内联视图法(inline View)
1 -- DML,0.019s
2 UPDATE (
3 SELECT
4 s.name sname, b.name bname
5 FROM
6 student s, boy b
7 WHERE
8 s.id = b.id AND s.name != b.name
9 )
10 SET sname = bname;
11
报错提示:ORA-01779: 无法修改与非键值保存表对应的列
参考资料,从表id必须增加主键约束,且为视图内的where条件:
1 -- DDL
2 ALTER TABLE boy ADD CONSTRAINT pk_id PRIMARY KEY (id);
5、合并法(Merge)
1 MERGE INTO student s USING boy b ON (
2 s.id = b.id AND s.sex = ‘boy‘ AND s.name != b.name
3 )
4 WHEN MATCHED THEN
5 UPDATE SET s.name = b.name;
报错提示:ORA-38104: 无法更新 ON 子句中引用的列
参考资料,错误原因是条件重复,正确写法:
1 -- DML,0.016s
2 MERGE INTO student s USING boy b ON (
3 s.id = b.id AND s.sex = ‘boy‘
4 -- AND s.name != b.name
5 )
6 WHEN MATCHED THEN
7 UPDATE SET s.name = b.name;
6、子查询关联
1 update service cs set (cs.customer_id,cs.customer_code,cs.customer_name)=
2 (
3 select ccb.customer_id,ccb.customer_code,ccb.customer_name from customer_base ccb
4 inner join customer_contact ccc
5 on ccb.customer_id=ccc.customer_id
6 where ccc.key_=‘1‘ and ccc.value_=cs.value_ and rownum<2
7 )
8 where customer_id=‘0‘ and start_time>sysdate-30