当我编写一个 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 都为空时,chk_col1 始终为 0。我试过了
coalesce(a.col1,'null') as coalesce(b.col1,'null')
但这也没有用。对于chk_col1,它仍然返回 1。
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 end) as chk_col1
from tablea a join
tableb b
on a.id = b.id;
就个人而言,我会将值保留为布尔值:
select a.id, a.col1 as a_col1, b.col1 as b.col1,
(a.col1 is distinct from b.col1) as chk_col1
from tablea a join
tableb b
on a.id = b.id;
另请注意,我使用了正确、明确、标准、可读JOIN
语法。
解决方案! : 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;