Update columns with values from related tables
This article explores how to update a column in a table (QuestionTrackings) whose values come from a related table (QuestionAnswers) based on a specific condition (QuestionID is NULL). We can achieve this using UPDATE statement combined with INNER JOIN.
SQL query:
UPDATE QuestionTrackings q
INNER JOIN QuestionAnswers a
ON q.AnswerID = a.AnswerID
SET q.QuestionID = a.QuestionID
WHERE q.QuestionID IS NULL
-- 可在此处添加其他条件
illustrate:
q.QuestionID IS NULL
Ensures that updates only affect rows in the QuestionTrackings table where QuestionID is NULL. Note:
Before executing an UPDATE query, it is recommended to preview the affected data. To do this, you can modify the query to include the following:
SELECT *
FROM QuestionTrackings q
INNER JOIN QuestionAnswers a
ON q.AnswerID = a.AnswerID
WHERE q.QuestionID IS NULL
-- 可在此处添加其他条件
This will display the rows that will be updated and confirm that each AnswerID has only one associated QuestionID to prevent data inconsistencies.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3