0

I have two tables, one Master and one ExtraData. Both tables share columns FirstName, LastName, Gender and A_Id.

The query I am working on should compare the two tables and UPDATE any NULL values for A_Id in Master using A_Id in Extra.

What is the best way to do this? I could compare CONCAT(FirstName, LastName, Gender) but I'm stuck on how to update the column based on a JOIN.

1 Answer 1

4

You can use many criteria in a join, and then simply set a column in one source table to the value of a column in the other table:

UPDATE Master 
JOIN ExtraData 
  ON Master.FirstName = ExtraData.FirstName
  AND Master.LastName = ExtraData.LastName
  AND Master.Gender = ExtraData.Gender
SET Master.A_Id = ExtraData.A_Id 
WHERE Master.A_Id IS NULL

Note that the JOIN condition can be made more succinct (because the columns are named the same): JOIN ExtraData USING (FirstName, LastName, Gender)

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh interesting, I've never understood USING before. That's far simpler than I expected. Thanks!
Yeah, USING is the only motivation I have for naming primary keys like this: student_id instead of students.id, since it makes it so easy :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.