简体   繁体   English

根据来自另一个表的联接更新MySQL NULL值

[英]Update MySQL NULL values based on join from another table

I have two tables, one Master and one ExtraData. 我有两个表,一个主表和一个ExtraData。 Both tables share columns FirstName, LastName, Gender and A_Id . 两个表共享列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. 我正在处理的查询应比较两个表,并使用Extra中的A_Id UPDATE Master中A_Id任何NULL值。

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 . 我可以比较CONCAT(FirstName, LastName, Gender)但我坚持如何基于JOIN更新列。

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) 请注意,可以使JOIN条件更加简洁(因为列的名称相同): JOIN ExtraData USING (FirstName, LastName, Gender)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM