我有一张表user
我需要更新,
user
表包含branchId
和accountName
。 branchId
是表格branch
上的fk参考,其中包含institutionId
。 InstitutionId
是对institution
表的FK引用。机构表包含name
和id
。
我想将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。任何帮助将不胜感激。
谢谢!。
答案 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