我想用另一个表中的匹配条件更新一个表。另一个表具有多个记录,因此只需要匹配键的前1个。到目前为止,这是我尝试过的:
UPDATE checkList
SET checkList.Answer = A.Answer,
checkList.Response = A.Response,
checkList.ANmbr = A.DisplayOrder
FROM checkList INNER JOIN (SELECT TOP 1 QuestID, Answer, Response, DisplayOrder FROM TabAnswers WHERE QuestID = checkList.QID ORDER BY DisplayOrder) A
ON A.QuestID = checkList.QID
WHERE checkList.auditid='158478' and checkList.Qtype = '0'
它没有从TabAnswers表中选择正确的数据。 TabAnswers对于给定的问题有多个答案,只需要在清单中填充第一个即可。 我找到了这个答案,但它是从表中选择第一个,而不是匹配克里特里亚 How to update column coming from TOP 1 of another table
答案 0 :(得分:2)
如果要从子查询的外部引用列,则需要使用CROSS APPLY代替INNER JOIN(或OUTER APPLY代替LEFT OUTER JOIN)。
始终在子查询中限定列也很重要。
UPDATE c
SET c.Answer = A.Answer,
c.Response = A.Response,
c.ANmbr = A.DisplayOrder
FROM checkList c
CROSS APPLY (SELECT TOP 1 ta.QuestID, ta.Answer, ta.Response, ta.DisplayOrder FROM TabAnswers ta WHERE ta.QuestID = c.QID ORDER BY DisplayOrder) A
WHERE c.auditid='158478' and c.Qtype = '0'