【问题标题】:PostgreSQL comparing null values in case statementPostgreSQL在case语句中比较空值
【发布时间】:2020-02-14 11:46:45
【问题描述】:

当我编写一个 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。

【问题讨论】:

    标签: sql postgresql null compare coalesce


    【解决方案1】:

    Postgres 支持 null 安全比较 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 语法。

    【讨论】:

      【解决方案2】:

      解决方案! : 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 来生成一些代码来比较表,这很方便。在这段代码中,我通过读取 svv_columns 元数据表创建了 2 个表,并且我想为每个变量创建一个 case 语句,因此我将每个表中的两个变量并排加上一个检查变量,我'd 用于稍后总结:

      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;
      

      【讨论】:

      • 注意:不幸的是,以上不适用于日期/时间字段。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2021-11-21
      相关资源
      最近更新 更多