SQL:field = other_field即使它们相同也返回false(NULL值)

pri*_*nce 1 sql postgresql comparison null

我有一个困难,因为在比较子查询中的两个字段时,尽管字段相同,即它们都具有NULL值,但比较返回FALSE结果

Therfore NULL = NULL返回FALSE

现在我知道NULL应该与IS运算符进行比较,但是当我比较两个字段时,我应该知道它们是否包含空值?如果值为NULL,我需要比较两个相同数据的字段.

考虑这个SQL:

SELECT 
*
FROM
fts.fts_customers_data_50360001
WHERE 
    fts.fts_customers_data_50360001.record_type = 15
    AND
    fts.fts_customers_data_50360001.mid = 103650360001
    AND NOT EXISTS
    (
        SELECT 
            fts.temp_fees_50360001.record_type
        FROM 
            fts.temp_fees_50360001
        WHERE 
            fts.temp_fees_50360001.record_type      = fts.fts_customers_data_50360001.record_type    
            AND 
            fts.temp_fees_50360001.merch_id         = fts.fts_customers_data_50360001.mid
            AND 
            fts.temp_fees_50360001.fee_curr         = fts.fts_customers_data_50360001.currency
            AND 
            fts.temp_fees_50360001.card_scheme      = fts.fts_customers_data_50360001.card_scheme
            AND 
            fts.temp_fees_50360001.tran_type        = fts.fts_customers_data_50360001.fee_type
            AND 
            fts.temp_fees_50360001.area             = fts.fts_customers_data_50360001.region
            AND 
            fts.temp_fees_50360001.srvc_type        = fts.fts_customers_data_50360001.card_type
    );
Run Code Online (Sandbox Code Playgroud)

在上面的查询中,

fts.temp_fees_50360001.card_scheme = fts.fts_customers_data_50360001.card_scheme

两者都有NULL值但比较返回false ..太糟糕了

任何想法都会得到很多赞赏

a_h*_*ame 6

正如其他人所指出的,NULL无法与之相提并论NULL.

在Postgres中,您可以使用操作符来缩短表达式,该操作符IS DISTINCT FROM是一个空的安全替代品<>.在你的情况下,你需要使用IS NOT DISTINCT FROM比较相等(看起来有点错误的方式,但遗憾的是IS EQUAL TO在SQL标准中没有相应的定义).

从手册:

当任一输入为空时,普通比较运算符产生null(表示"未知"),而不是true或false.例如,7 = NULL产生null,7 <> NULL也是如此.如果此行为不合适,请使用IS [NOT] DISTINCT FROM构造:

所以,而不是

(fts.temp_fees_50360001.record_type = fts.fts_customers_data_50360001.record_type
 OR (fts.temp_fees_50360001.record_type IS NULL 
     AND fts.fts_customers_data_50360001.record_type IS NULL)
)
Run Code Online (Sandbox Code Playgroud)

您可以使用:

(fts.temp_fees_50360001.record_type IS NOT DISTINCT FROM  fts.fts_customers_data_50360001.record_type)
Run Code Online (Sandbox Code Playgroud)

自动处理NULL值.如果你想比较相等但是它仍然很短,那么这个条件看起来有点奇怪.