【问题标题】:How to properly compare nullable fields for equality?如何正确比较可空字段是否相等?
【发布时间】:2012-11-21 05:36:42
【问题描述】:

在任何数据库中,使用coalesce() 来比较可空字段是否相等似乎是一种常见做法。例如,如果您要比较两个可为空的字符串字段,您将使用where coalesce(tbl1.stringfield,'') = coalesce(tbl2.stringfield,'')。这是有效的,因为'' 的空字符串在上下文中可以很好地转换为null

但是,如果您要处理的数据类型(例如日期或数字)没有“空”等价物,该怎么办?在 Teradata 中,如果您尝试使用 where coalesce(tbl1.numberfield,'') = coalesce(tbl2.numberfield,''),如果其中一个字段不为空,则会收到数据类型不匹配错误。这是因为它试图将数字与空字符串进行比较。要让它工作,你必须使用where coalesce(tbl1.numberfield,0) = coalesce(tbl2.numberfield,0)。但是,如果 tbl1.numberfield 为 null 而 tbl2.numberfield 实际上包含 0 的值怎么办? WHERE 条件将返回 true,而实际上它应该返回 false,因为一个值为 null,另一个为 0。我能看到的唯一解决方法是这个非常笨拙的案例逻辑:

where case
    when 
        (tbl1.numberfield is null and tbl2.numberfield is null) or
        (tbl1.numberfield is not null and tbl2.numberfield is not null) or
        tbl1.numberfield <> tbl2.numberfield
    then 1
    else 0
end = 1

如果允许将两个空值与一个简单的等号进行比较,那么所有这些都可以避免。

【问题讨论】:

    标签: null nullable teradata coalesce


    【解决方案1】:

    为什么不直接

    SELECT * FROM TABLE A, TABLE2 B WHERE A.a = B.a or ( A.a is NULL and b.A is NULL)
    

    这是在我熟悉的可空字段上检查权益的标准,它应该适用于所有情况。它对读者来说更直接,应该运行得更快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-14
      • 2014-09-20
      • 2012-02-15
      • 2015-03-13
      • 2015-09-16
      • 1970-01-01
      相关资源
      最近更新 更多