[英]2 same tables, update second table where data exists in table 1
I have 2 tables with the same columns. 我有2个具有相同列的表。 for example 例如
table 1
id
name
height
weight
table 2
id
name
height
weight
The data is table 2 is complete. 数据是表2完成的。 But in table 1, only some data exists, and the rest of the columns are empty. 但是在表1中,仅存在一些数据,其余列为空。 for example: 例如:
table 1 table 2
id 4 4
name (empty) salman
height 5'11" 5'9"
weight (empyy) 65kg
I want a single script, that will allow me to update the table 2 with values from table 1, but only where it exists. 我想要一个脚本,该脚本将允许我使用表1中的值来更新表2,但仅在它存在的地方。 In places where the table 1 is empty, I want to retain the data that already exists in table 2. 在表1为空的地方,我想保留表2中已经存在的数据。
I've tried various ways, but all required multiple queries and are long and hectic. 我尝试了各种方法,但是所有方法都需要多个查询,而且又很忙。 I want to know if there is a simpler way to get this done? 我想知道是否有更简单的方法来完成此任务? Preferably in a single query? 最好在单个查询中?
Thank you 谢谢
You can try by joining the 2 tables and then using the CASE keyword to conditionally update the fields: 您可以尝试通过联接2个表,然后使用CASE关键字有条件地更新字段:
UPDATE table2 t2 INNER JOIN table1 t1 USING (id)
SET
t2.name = CASE WHEN (t1.name IS NULL) THEN t2.name ELSE t1.name END
t2.height= CASE WHEN (t1.height IS NULL) THEN t2.height ELSE t1.height END
t2.weight = CASE WHEN (t1.weight IS NULL) THEN t2.weight ELSE t1.weight END
http://dev.mysql.com/doc/refman/5.5/en/case-statement.html http://dev.mysql.com/doc/refman/5.5/zh-CN/case-statement.html
http://dev.mysql.com/doc/refman/5.5/en/update.html http://dev.mysql.com/doc/refman/5.5/en/update.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.