有没有一种快速方法可以在 SQL 中比较两个格式相同的表?

发布于 2024-09-06 14:45:30 字数 340 浏览 3 评论 0原文

我想做一个 SQL 查询来比较两个具有相同列(名称和类型)的表。每个表都有一个唯一的键。我希望查询返回包含不相等值的任何行。我知道可以做这样的事情

select * 
from table_1, table_2
where 
table_1.key = table_2.key
and (
 table_1.col1 != table_2.col1 OR
 table_1.col2 != table_2.col2 OR
 ...

)

,但这会很乏味,因为有大量且可能可变的列数。

编辑

如果有帮助,我正在使用 tsql 系统。

I would like to make an SQL query to compare two tables with identical columns, both names and types. Each table has a unique key. I want the query to return any rows that contain unequal values. I know could do something like this

select * 
from table_1, table_2
where 
table_1.key = table_2.key
and (
 table_1.col1 != table_2.col1 OR
 table_1.col2 != table_2.col2 OR
 ...

)

but this would be tedious since there are a large and potentially variable number of columns.

edit

If it helps, I'm using a tsql system.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

极度宠爱 2024-09-13 14:45:30

不确定您使用的数据库类型,但如果您使用 SQL Server 2005 或更高版本,请尝试以下操作:

select 'table1' as tblName, *  from
  (select * from table1
   except
   select * from table2) x
union all
select 'table2' as tblName, *  from
  (select * from table2
   except select * 
   from table1) x

Not sure what type of DB you are using but if you are using SQL Server 2005 or higher try this:

select 'table1' as tblName, *  from
  (select * from table1
   except
   select * from table2) x
union all
select 'table2' as tblName, *  from
  (select * from table2
   except select * 
   from table1) x
当爱已成负担 2024-09-13 14:45:30

这怎么办..

select * from table1 where not exists (select * from table2)
union all
select * from table2 where not exists (select * from table1)

How abt this..

select * from table1 where not exists (select * from table2)
union all
select * from table2 where not exists (select * from table1)
辞慾 2024-09-13 14:45:30

通过 SQL Server 验证:

(select * from table1 except select * from table2)
    union
(select * from table2 except select * from table1);

通过 Oracle 验证:

(select * from table1 minus (select * from table2))
    union
(select * from table2 minus (select * from table1))

Verified with SQL Server:

(select * from table1 except select * from table2)
    union
(select * from table2 except select * from table1);

Verified with Oracle:

(select * from table1 minus (select * from table2))
    union
(select * from table2 minus (select * from table1))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文