使用 table1.* <> table2.* 时发生了什么?



想象一下,两个表具有相同的结构,但对于相同的主键,可能有一些行不相等。

当使用这样的where子句时,实际发生了什么:";where table1.* <> table2.*"?

我"使用";它在PostgreSQL中,但我对其他语言的行为很感兴趣。

此语句将第一个表的每一列一起与第二个表的每个列一起

(t1.id, t1.col1, t1.col2) <> (t2.id, t2.col2, t2.col2)

或者更详细的

t1.id <> t2.id
OR t1.col1 <> t2.col1
OR t1.col2 <> t2.col2

但是,您可能希望使用IS DISTINCT FROM而不是<>来认为null vs not null不同/不相等。

在postgres t1.*<gt;t2.*在此上下文中被扩展为:

(t1.c1, t1.c2, ..., t1.cn) <> (t2.c1, t2.c2, ..., t2.cn)

与相同

(t1.c1 <> t2.c1) OR (t1.c2 <> t2.c2) OR ...

我认为扩展是对标准的后期扩展,元组比较存在于其他几个DBMS中。你可以在上阅读https://www.postgresql.org/docs/current/sql-expressions.html#SQL-语法行结构

比较元组时要求列数相同,但是我在尝试你的例子时发现了一些奇怪的东西:

create table ta (a1 int);
create table tb (b1 int, y int);
select * from ta cross join tb where ta.* <> tb.* 

最后一次选择成功,尽管元组具有不同的列数。添加一些行可以改变:

insert into ta values (1),(2);
insert into tb values (2,1),(3,4);
select * from ta cross join tb where ta.* <> tb.* 
ERROR:  cannot compare record types with different numbers of columns

因此,在准备语句时,它显示为未选中此项。即使使用空表,手动扩展元组也会产生错误:

select * from ta cross join tb where (ta.a1, ta.a1) <> (tb.b1, y, y); 
ERROR:  unequal number of entries in row expressions

Fiddle

相关内容

最新更新