4.10 用其他表中的值更新

问题:

要用一个表中的值来更新另外一个表中的行。例如,在表new_sal中保存着某个特定员工的新工资.

在表new_sal中,deptno为关键字。要用表new_sal中的值更新表emp中相应员工的工资,条件是emp.deptno与new_sal.deptno相等,将匹配记录的emp.sal更新为new_sal.sal,将emp.comm更新为new_sal.sal的50%。

解决方案:
在表new_sal和emp之间做链接,用来查找comm新值并带给update语句。像这样通过关联子查询进行更新的情况十分常见;另一种方法是创建视图(创建视图或内联视图,视数据库支持而定),然后更新这个视图。

使用相关的子查询来设置表emp中的sal和comm值,同样使用相关的子查询判别表emp中哪些行需要被更新:

update emp e 
    set (e.sal,e.comm)  = (select ns.sal,ns.sal/2 from new_sal ns 
                                    where ns.deptno = e.deptno)
where exists(select null from new_sal ns 
            where ns.deptno = e.deptno)

原文地址:https://www.cnblogs.com/liang545621/p/7518755.html