SQL UPDATE SET 一列等于另一列引用的相关表中的值?

新手上路,请多包涵

我希望这是有道理的,让我详细说明:

有一个测验程序的跟踪数据表,其中每一行都有..

QuestionID 和 AnswerID(每个都有一个表)。因此,由于一个错误,有一堆 QuestionID 设置为 NULL,但相关 AnswerID 的 QuestionID 位于 Answers 表中。

假设 QuestionID 为 NULL,AnswerID 为 500,如果我们转到 Answers 表并找到 AnswerID 500,则有一列 QuestionID 应该是 NULL 值所在的位置。

所以基本上我想将每个 NULL QuestionID 设置为等于在跟踪表中 AnswerID 的 Answer 行上的 Answers 表中找到的 QuestionID(与正在写入的 NULL QuestionID 相同的行)。

我该怎么做?

 UPDATE QuestionTrackings
SET QuestionID = (need some select query that will get the QuestionID from the AnswerID in this row)
WHERE QuestionID is NULL AND ... ?

不确定我如何能够将 QuestionID 从匹配的 AnswerID 分配给 QuestionID …

原文由 MetaGuru 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答
update QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
set q.QuestionID = a.QuestionID
where q.QuestionID is null -- and other conditions you might want

我建议在运行更新之前检查要更新的结果集是什么(相同的查询,只需选择):

 select *
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want

特别是每个答案 id 是否肯定只有 1 个关联的问题 id。

原文由 eglasius 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果是 Postgres 你必须使用以下结构:

 UPDATE table1
SET colX = table2.colY
FROM table2
WHERE table1.id = table2.id;

原文由 Radu Linu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进