我有 2 个具有相同列的表。例如
table 1
id
name
height
weight
table 2
id
name
height
weight
数据如表2所示为完整数据。但在表 1 中,仅存在一些数据,其余列为空。例如:
table 1 table 2
id 4 4
name (empty) salman
height 5'11" 5'9"
weight (empyy) 65kg
我想要一个脚本,它将允许我使用表 2 中的值更新表 1,但仅限于它存在的地方。在表 1 为空的地方,我想保留表 2 中已经存在的数据。
我已经尝试了各种方法,但都需要多次查询,而且又长又忙。我想知道是否有更简单的方法来完成这项工作?最好在单个查询中?
谢谢
您可以尝试连接 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/en/update.html