Null 如何正确比较可为空的字段是否相等?

Null 如何正确比较可为空的字段是否相等?,null,nullable,teradata,coalesce,Null,Nullable,Teradata,Coalesce,在任何数据库中,使用coalesce()比较可空字段是否相等似乎是一种常见做法。例如,如果要比较两个可为空的字符串字段,可以使用where coalesce(tbl1.stringfield“”)=coalesce(tbl2.stringfield“”)。这是因为'的空字符串在上下文中可以很好地转换为null 但是,如果您处理的数据类型(如日期或数字)没有“空”等价物,该怎么办?在Teradata中,如果尝试其中coalesce(tbl1.numberfield“”)=coalesce(tbl2

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

但是,如果您处理的数据类型(如日期或数字)没有“空”等价物,该怎么办?在Teradata中,如果尝试
其中coalesce(tbl1.numberfield“”)=coalesce(tbl2.numberfield“”)
,如果其中一个字段不为null,则会出现数据类型不匹配错误。这是因为它试图将数字与空字符串进行比较。要使其工作,必须使用
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
where case
什么时候
(tbl1.numberfield为空,tbl2.numberfield为空)或
(tbl1.numberfield不为空,tbl2.numberfield不为空)或
tbl1.numberfield tbl2.numberfield
那么1
其他0
结束=1
如果允许用一个简单的等号比较两个空值,那么所有这些都可以避免

SELECT * FROM TABLE A, TABLE2 B WHERE A.a = B.a or ( A.a is NULL and b.A is NULL)
这是我熟悉的检查可空字段的公平性的标准,在所有情况下都应该有效。这对读者来说更直接,应该跑得更快