引用以下SQLFiddle:http://sqlfiddle.com/#!2/f02ca/1
我有两个几乎相同的表。我想确定表数据之间的差异,用另一个表的不同数据更新一个表。
table1
|| *id* || *some_id* || *timestamp* ||
|| 1 || A || 01:00 ||
|| 2 || B || 02:00 ||
|| 3 || B || 01:00 ||
|| 4 || A || 02:00 ||
|| 5 || A || 03:00 ||
table2
|| *id* || *some_id* ||
|| 1 || B || <-- some_id is different than table1
|| 2 || B ||
|| 3 || B ||
|| 4 || A ||
|| 5 || B || <-- some_id is different than table1
所以我想用新的 some_id
更新表 1来自表 2。我可以很容易地找到两个表之间的差异:
SELECT t2.id
FROM table2 t2
LEFT JOIN table1 t1 ON t1.id = t2.id
WHERE t2.some_id != t1.some_id
结果:
1, 5 (the id's of the table2 rows that have a different some_id).
我以为我可以做这种类型的查询:
UPDATE table1
SET some_id =
(SELECT some_id FROM table2 WHERE id IN
(SELECT t2.id
FROM table2 t2
LEFT JOIN table1 t1 ON t1.id = t2.id
WHERE t2.some_id != t1.some_id ))
我认为查询会更新 table1
新some_id
来自 table2
但仅适用于 some_ids
所在的行他们之间有什么不同。但是我收到以下错误:
SQL Error (1093): You can't specify target table 'table1' for update in FROM clause
我走在正确的轨道上吗?如果是这样,我该如何解决这个问题?有没有更好或更有效的方法来实现这一目标?
一些注意事项:
- 重要的是我不只是更新或插入
table2
中的所有内容进入table1
, 因为timestamp
柱子。当行更新时,该列将自行更新。我想在table1
中更新的唯一行是some_id
的行table2
不同.所以本质上,timestamp
列显示该行最后一次更改的时间。 - 重要的是要尽可能少地查询并高效地完成这项工作。在我这里的简单示例中,每个表只有 5 行,但实际上我的表有数千行。
最佳答案
您可能需要一个带有 JOIN 的更新:
UPDATE table1 AS t1
INNER JOIN table2 AS t2
ON t1.id = t2.id
SET t1.some_id = t2.some_id
WHERE t1.some_id != t2.some_id
;
连接基本上与您的 SELECT 语句中的相同,只是它不需要是外部连接,因为据我了解,您只想更新 id
匹配的行。
这是此查询的 SQL Fiddle 演示:http://sqlfiddle.com/#!2/58eb8/1 .
关于mysql - 有效地将表2中的值合并到表1中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15327296/