鉴于表B中的以下记录,其中:
B.Id | B.CId | B.Name
1 | 1 | "apple"
2 | 2 | "apple"
3 | 1 | "banana"
4 | 2 | "banana"
在表A中,我有值:
A.Id | A.BId | A.CId
1 | 1 | 2
2 | 4 | 1
实际上需要更新为:
A.Id | A.BId | A.CId
1 | 2 | 2
2 | 3 | 1
基于以下事实:A.CId需要使用A.BId,其中B.CId匹配,而B.Name匹配A.BId的.Name。
答案 0 :(得分:1)
尝试以下方法:
SET bid = b.id --setting the value for bid to the id value in table b
FROM b b JOIN a a on a.cid = b.cid --where the cid cols in each table match
WHERE b.id IN
(SELECT b1.id from b b1 join a a1 on a1.bid = b1.id WHERE b1.name = b.name)
--and table b's ID is for row with a name value matching when joined on the
--foreign key instead of cid
这里是对涉及多个表的sql update语句的引用: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/1022bbce-3d99-49d1-83a1-75bafa49ac25/tsql-update-statement-with-join
答案 1 :(得分:0)
听起来像是update ... from ...
的工作,请参阅UPDATE (Transact-SQL)。
update
A
set
BId = B.Id
from
B
where
A.CId = B.CId
这里以SQLFiddle为例。