【问题标题】:Checking if contents of two table are identical in MySQL在 MySQL 中检查两个表的内容是否相同
【发布时间】:2020-07-16 12:41:41
【问题描述】:

我在两个数据库 V1 和 V2 中有相同的列 col1、col2 集的视图。

现在我想知道它们是否包含相同的行。在这种情况下,我浏览了这篇文章:SQL compare data from two tables

在此之后,我正在运行以下查询:

  select * from v1.A
  minus
  select * from v2.A;

但我收到以下错误:

 ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select * from v2.A' at line 3

我没有得到任何关于如何修复此错误的线索。

【问题讨论】:

  • 我想知道它们是否包含相同的行 identical 是什么意思?为什么返回相同行数的 2 个数据集相同
  • @forpas,我有一个用例,我正在运行两个实验并将数据转储到具有相同架构的两个不同数据库的两个表中。
  • 很好,但我确定您不希望考虑具有相同行数的相同 2 个表,对吗?我的问题是在您接受完全符合此要求的答案后发布的。
  • 是的,你完全正确。 @forpas,我错误地接受了这一点。我意识到即使两个表中的字段值不同,我也会得到 count1+count2=count3

标签: mysql mysql5


【解决方案1】:

你可以用NOT EXISTS模拟MySql中不支持的minus

select t1.* from v1.A t1
where not exists (
  select * from v2.A t2
  where t2.col1 <=> t1.col1 and t2.col2 <=> t1.col2
)

我使用 NULL 安全相等运算符 &lt;=&gt; 而不是只使用 = 以防万一有需要比较的 nulls。

但是,如果这个查询没有返回任何结果,这并不意味着这两个视图返回了相同的行,因为v1.A 可能会返回v1.B 返回的行的子集。
所以你还需要:

select t2.* from v2.A t2
where not exists (
  select * from v1.A t1
  where t2.col1 <=> t1.col1 and t2.col2 <=> t1.col2
)

也许更好的是 2 个查询中的 UNION ALL

select 1 from_view, t1.* from v1.A t1
where not exists (
  select * from v2.A t2
  where t2.col1 <=> t1.col1 and t2.col2 <=> t1.col2
)
union all
select 2 from_view, t2.* from v2.A t2
where not exists (
  select * from v1.A t1
  where t2.col1 <=> t1.col1 and t2.col2 <=> t1.col2
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2012-03-29
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    相关资源
    最近更新 更多