- 需求
有表成绩T1,记录学生成绩,表T2是一张加分的表,现在用表T2给少数名族学生加分。 - 表成绩表T1
PID score ISMINORITY
---- ---------- ----------
1 670 N
2 620 N
3 600 N
4 520 Y
5 480 N
6 568 Y
- 表T2(加分表)
PID ADD_score
---- ----------
3 21
4 100
6 100
- 写法1(可能有潜在error)
MERGE INTO T1 USING T2 ON (T1.PID = T2.PID) WHEN MATCHED THEN UPDATE SET T1.score = T1.score + T2.ADD_score WHERE T1.ISMinority = 'Y';
写法1有潜在error是因为Merge
不能多次更新被更新表(即T1)的同一条记录,如果T2有重复的数据,比如两条pid为4的记录。那么写法1将报错
ORA-30926: unable to get a stable set of rows in the source tables
但是如果T2有两条pid为3则不会报错
- 升级版写法
MERGE INTO T1 USING (SELECT PID,MAX(add_score) add_score FROM t2 GROUP BY PID) T2 ON (T1.PID = T2.PID) WHEN MATCHED THEN UPDATE SET T1.score = T1.score + T2.ADD_score WHERE T1.ISMinority = 'Y';