---
title: "关于联表更新"
author: "zhengxuezhou"
date: "2010-09-21T13:49:31Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2011-07-14T11:05:53Z"
id: 769027
url: "https://fire11.iteye.com/blog/769027"
---

实例sql:
update tblnmdevice t1 set t1.keystr = (select t2.displayname from tblbusinesssys t2 join tblbusinessdeviceunion t3 on t2.tbluuid = t3.businessid where t3.devicepath =t1.devicepath)
        where exists (select 1 from tblbusinessdeviceunion t4 where t4.devicepath = t1.devicepath);


比如a 表中的某个字段复制到B表中指定的字段，前提是a表中主键和b表的外键对应的记录才更新；

update sfinaareacode a set a.areano=
(select b.areano from sareacode b where a.finaareacode=b.areacode)
where exists (select 1 from sareacode b where a.finaareacode=b.areacode)

解释：

where exists (select 1 from sareacode b where a.finaareacode=b.areacode)表示

这条记录存在，也就是说没有记录是不更新，这样可以保证不在这个记录范围内的
a.areano不会被更新

当(select 1 from sareacode b where a.finaareacode=b.areacode)存在的时候，才更新数据 1可以替换其它的值，都可以，只是一个常量