在MySQL中检查两个表的内容是否相同

  • 本文关键字:是否 两个 MySQL mysql mysql5
  • 更新时间 :
  • 英文 :


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

现在我想知道它们是否包含相同的行。在本文中,我已经阅读了这篇文章:SQL比较来自两个表的数据。

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

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

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

您可以使用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安全相等运算符<=>而不是仅使用=,以防需要比较null

但如果此查询未返回任何结果,并不意味着这两个视图返回相同的行,因为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
)

也许最好是两个查询中的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
)

最新更新