我有两个结构相同的表,table2 是将用于批量更新 table1 的新数据的集结地。
我需要找出表 1 中哪些行将被更新。我想忽略那些将被插入的行和那些将被删除的行。我只对更新的行感兴趣,其中主键保持不变但行中的一个或多个其他字段包含不同的数据。
到目前为止,我最接近的是以下声明。
SELECT table2.* FROM table2
INNER JOIN table1
ON table1.primarykey = table2.primarykey
WHERE table1.field1 != table2.field1
OR table1.field2 != table2.field2
OR table1.field3 != table2.field3
这将返回 0 行。
编辑:查询确实有效。数据本身有问题。我要去 facepalm 一段时间。
谢谢大家的意见。
最佳答案
您没有考虑的一件事是空值。这可能是也可能不是您的问题,因为它取决于数据
SELECT table2.* FROM table2
INNER JOIN table1
ON table1.primarykey = table2.primarykey
WHERE table1.field1 != table2.field1
OR table1.field2 != table2.field2
OR table1.field3 != table2.field3
OR (table1.field1 is null and table2.field1 is not null)
OR (table2.field1 is null and table1.field1 is not null)
OR (table1.field2 is null and table2.field2 is not null)
OR (table2.field2 is null and table1.field2 is not null)
OR (table1.field3 is null and table2.field3 is not null)
OR (table2.field3 is null and table1.field3 is not null)
关于MySQL比较两个表,返回主键相同但其他字段数据不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9433950/