gpt4 book ai didi

sql - PostgreSQL 查询两个表之间的相等性

转载 作者:行者123 更新时间:2023-11-29 14:05:35 26 4
gpt4 key购买 nike

我有两个表 A 和 B,我想要一个查询:仅当两个表相同时才返回 TRUE(我的意思是 A 中的每一行都存在于 B 中,反之亦然,无论行顺序如何)

我使用了关键字 EXCEPT 但在很多情况下它不起作用

感谢您的帮助。

最佳答案

select * from tablea except all select * from tableb

返回 tablea 中不存在于 tableb 中的所有行。

反之亦然

select * from tableb except all select * from tablea

返回 tableb 中不存在于 tablea 中的所有行。

所以,现在我们可以:

select count(*) from ( select * from tablea except all select * from tableb ) x;

获取 tablea 中“坏”行的数量,并且:

select count(*) from ( select * from tableb except all select * from tablea ) x;

获取 tableb 中“坏”行的数量。

如果两个计数都为 0,则表相同。并且由于两个计数都不能小于零,因此我们可以测试计数之和是否为 0:

select 0 = ( select count(*) from ( select * from tablea except all select * from tableb ) x ) + ( select count(*) from ( select * from tableb except all select * from tablea ) x );

关于sql - PostgreSQL 查询两个表之间的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1973869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com