MySQL比较两个表,返回主键相同但其他字段数据不同的行

标签 mysql sql

我有两个结构相同的表,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/

相关文章:

mysql - 水平连接 n 个结果集

php - 如何将字符串变量放在 mysql_resutl 字段中?

sql - 从 sql server 中的字符串转换日期和/或时间时转换失败

mysql - 选择三个表并计数

php - 更新查询语法

mysql - 不等于子字符串数组的地方

sql - MySQL 从临时表返回单行

mysql - 根据结果​​条件在 mysql 查询中插入或省略条目

sql - 重新分配移动操作序号的最佳方法是什么

C# XAML UWP InvalidCastException 与 MySQL