【发布时间】:2014-10-13 10:18:48
【问题描述】:
假设我有一个包含这些列和值的表:
id field
-----------
1 0001
2 0002
3 0003
4 0004
5 0005
然后我有另一个包含这些字段和值的表:
id tid info_1 field_1 info_2 field_2
---------------------------------------------------
1 1 7 0000 null null
2 2 null null 10 0002
3 3 17 0003 null null
4 4 29 1111 null null
5 6 null null 44 0005
我需要一个更新查询来更新表 2 的记录,仅在 info 列中,但前提是表 1 在表 2 中有匹配的字段,并且仅当第一个表的 id 和第二个表的 tid 匹配时。
因此,例如表 1 id 为 1 和表 2 tid 为 1 匹配,但 field_1 或 field_2 的字段编号与表 1 不同。
表 1 id of 2 和表 2 tid of 2 匹配,field_2 确实有一个匹配的数字作为表一中的字段,所以我想将表 2 的记录 2 的 info_2 更改为我选择的数字。假设是 50。在所有情况下,info_1 或 info_2 中的数字都将更改为 50。
现在表 1 id 为 3 和表 2 tid 为 3 匹配,并且 field_1 与表 1 中的字段匹配,因此我需要将表 2 中的第 3 条记录的 info_1 更改为 50。
在记录 4 中,id 和 tid 匹配,但没有字段匹配,所以跳过那个。
在记录5中,即使表2的field_2与表一的字段匹配,但第一表的id和第二表的tid不匹配,所以可以跳过第5条记录。
这是我目前尝试过的:
$updatequery1 = "UPDATE table2 LEFT JOIN table1 a ON a.field = field_1 SET info_1 = 50";
$updateresult1 = mysql_query($updatequery1) or die(mysql_error());
所以对于第一次尝试,我没有设置 id 和 tid 来匹配,我只是去寻找字段匹配。我也没有合并 field_2。甚至不确定是否可以一次性完成,或者是否需要多个查询。无论如何,即使没有字段匹配,此尝试也会使所有 info_1 值等于 50。
如果可能的话,有人可以帮我处理这个查询并让两个信息列同时更改吗?
如果我要进行选择查询以选择在表 1 id 和表 2 tid 中匹配的所有记录,它会是这样,但不知道如何将其合并到更新查询中。
SELECT table1.*, table2.*
FROM table1
LEFT JOIN table2
ON table1.id = table2.tid
我也可以尝试合并字段匹配,它可能是这样的:
SELECT table1.*, table2.*
FROM table1
LEFT JOIN table2
ON table1.id = table2.tid
WHERE table1.field = table2.field_1
OR table1.field = table2.field_2
但同样,不知道如何将其转换为更新查询,以便 info_1 或 info_2 相应地更改。
因此,以更快的方式进行总结。如果 id 和 tid 匹配并且 field 和 field_1 匹配,info_1 应该变为 50。如果 id 和 tid 匹配并且 field 和 field_2 匹配,info_2 应该变为 50
【问题讨论】:
-
只用一个case语句..
SET t2.info_1 = CASE WHEN t1.id = t2.I'd THEN 50 ELSE NULL END