【问题标题】:MySQL compare two tables and return rows that have the same primary key but different data in other fieldsMySQL比较两张表,返回主键相同但其他字段数据不同的行
【发布时间】:2012-02-24 16:03:34
【问题描述】:

我有两个结构相同的表,table2 是用于批量更新 table1 的新数据的中转站。

我需要找出 table1 中哪些行将被更新。我想忽略那些将被插入和那些将被删除的行。我只对更新后的行感兴趣,其中主键保持不变,但行中的一个或多个其他字段包含不同的数据。

到目前为止,我最接近的是以下声明。

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 行。

编辑:查询确实有效。数据本身存在问题。我会去打脸。

感谢大家的意见。

【问题讨论】:

  • 正如康拉德所说,null 不等于 null,因此您必须在比较时考虑到这一点 - 您编写它的方式,数据可能“相同”但会显示如果那里有空值,则不相等。
  • 另外,如果您使用允许它的存储引擎,为什么不关闭自动提交,运行更新并查看发生了什么变化,然后回滚?
  • @Poodlehat:这是个好主意,但你将如何“看到”发生了什么变化?
  • 嗯,这真的取决于你到底需要做什么。如果它处于离线状态,我只需保存两个 csv 文件并在我选择的比较工具中查看它们......但是你不需要这个查询,现在是吗? :)
  • 我将不得不考虑空值,因为我对此一无所知。但是,我已经剥离了我的查询,因此没有 where 子句,并且内部连接似乎没有连接所有匹配的行。

标签: mysql sql


【解决方案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
      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)

【讨论】:

    【解决方案2】:

    换句话说,您想在 table2 中计算有多少行的主键与 table1 中的相同,并且至少有一个字段不同,对吧?但是数据是否不同又有什么关系呢?如果数据相同,则 UPDATE 无效。

    SELECT
       COUNT(T2.*) 
    FROM
       table2 AS T2
    JOIN table1 AS T1 ON (T1.primarykey = T2.primarykey);
    

    【讨论】:

    • 这实际上并没有回答问题,也许您没有阅读整个问题?在那里跳了一点枪
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多