通过连接多个表

时间:2018-06-07 15:28:32

标签: sql sql-server database sql-server-2008

我有一张表user我需要更新,

user表包含branchIdaccountNamebranchId是表格branch上的fk参考,其中包含institutionIdInstitutionId是对institution表的FK引用。机构表包含nameid

我想将accountName表中的user更新为该用户的等效机构名称。

我目前拥有的是

update [user] set accountName = 
(Select i.NAME from institution i LEFT JOIN [branch] b on b.institution_id = i.id and b.id = branchId) 

但我正在

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   一种表达。声明已经终止。

我正在使用mssql

我不是专业人士使用sql。任何帮助将不胜感激。

谢谢!。

2 个答案:

答案 0 :(得分:2)

试试这个:

UPDATE u
SET u.accountName = i.name
FROM User u
JOIN Branch b ON b.id = u.branchId
JOIN Institution i ON i.id = b.institutionId

答案 1 :(得分:0)

您需要将目标表与源连接。首先创建一个SELECT查询

Select i.NAME, u.accountName
from institution i 
JOIN [user] u
on {set suitable criteria}
LEFT JOIN [branch] b on b.institution_id = i.id and b.id = branchId

并检查这是否返回了正确的结果。将SELECT替换为UPDATE,如下所示:

update u set accountName = i.NAME
from institution i 
JOIN [user] u
on {set suitable criteria}
LEFT JOIN [branch] b on b.institution_id = i.id and b.id = branchId
相关问题