PostgreSQL比较case语句中的空值

问题描述 投票:0回答:1

当我编写一个case语句以比较表中的值时,它没有被变量null阻塞。它认为它们是不同的(注意:col1是一个字符字段)。

select a.id,
       a.col1 as a_col1,
       b.col1 as b.col1,
       case when a.col1=b.col1 then 0 else 1 end as chk_col1
from   tablea a,
       tableb b
where a.id=b.id;

...当两个col1均为null时,chk_col1始终为0。我已经尝试过

coalesce(a.col1,'null') as coalesce(b.col1,'null')

但是这也不起作用。 chk_col1仍然返回1。

sql postgresql null compare coalesce
1个回答
0
投票

解决方案! :colaesce函数中引用的变量必须是计算得出的变量,即

coalesce(a_col1,'null') as coalesce(b_col1,'null')

我发现了另一件事。假设col2是数字。上面的方法不起作用,您需要使用0。或者...更狡猾的是,您可以使用'0',即

coalesce(a_col2,'0') as coalesce(b_col2,'0')

这很容易知道您是否要通过引用pg_tables或svv_columns生成一些代码来比较表。在这段代码中,我有2个表是通过读取svv_columns元数据表创建的,并且我想为每个变量创建一个case语句,因此我将并排使用每个表中的两个变量以及一个检查变量将在以后进行总结:

select '       coalesce(a.'||a.column_name||',''0'') as a_'||a.column_name||', coalesce(b.'||b.column_name||',''0'') as b_'||b.column_name||', case when a_'||a.column_name||'=b_'||b.column_name||' then 0 else 1 end as chk_'||a.column_name||','
from   tbl_a_vars a,
       tbl_b_vars b
where a.column_name=b.column_name;

0
投票

Postgres支持空安全比较operator is not distinct from。因此,请尝试:

select a.id,
       a.col1 as a_col1,
       b.col1 as b.col1,
       (case when a.col1 is not distinct from b.col1 then 0 else 1 end0 as chk_col1
from tablea a join
     tableb b
     on a.id = b.id;
© www.soinside.com 2019 - 2024. All rights reserved.