merge and update

前些天要更新一张表inhabitant的一个字段relationshipwithhead,只是更新一部分,这一部分数据我保存在了另外一张表inhabitant_up中,包括id和需要更新的字段relationshipwithhead的值。

接着我想到了update语句

update inhabitant i set i.relationshipwithhead =(select u.relationshipwithhead from inhabitant_up u where i.id=u.id)

结果这句话是错误的,因为这张表会进行全表更新,因为后面的select语句会返回一个值,如果找到id相等的就返回更新的值,如果没有则返回null,这样不需要更新的也更新了,并且值为null,出现错误。

其实这个业务可以用merge,更新匹配的数据,不匹配的就不用更新。

merge into inhabitant i
using inhabitant_up u
on(i.id=u.id)
when matched then
update
set i.relationshipwithhead=u.relationshipwithhead

这样就只更新哪些需要更新的数据,没有更新的则不变。

原文地址:https://www.cnblogs.com/xz1367/p/2232583.html