比较 Snowflake 上包含 NULL 值的两个表

Compare Two Tables on Snowflake Where it Contains NULL Values

大家好,我遇到了一个问题,即 Table T1 架构

ID TYPE MODEL_ID FREQ
1 Car 234 5
2 SUV 12 6
3 EV NULL NULL
4 HV NULL NULL

TABLE T2 模式和数据

ID TYPE MODEL_ID FREQ
3 EV NULL NULL
4 HV NULL NULL

现在我正在使用以下查询检查工作情况,

SELECT *  FROM T1 AS T, T2 AS N
  WHERE T.ID = N.ID AND T.TYPE = N.TYPE AND T.MODEL_ID = N.MODEL_ID AND T.FREQ = N.FREQ

结果为空集,我知道我需要实现一个空安全查询但是对于这种情况我该如何实现。

注意:这里的ID不是标识符,所以要和table中的每一列进行比较。

您可以使用 IS NOT DISTINCT FROM 执行 NULL 安全比较:

Compares whether two expressions are equal (or not equal). The function is NULL-safe, meaning it treats NULLs as known values for comparing equality.

SELECT *  
FROM T1 AS T, T2 AS N 
WHERE T.ID       IS NOT DISTINCT FROM N.ID 
  AND T.TYPE     IS NOT DISTINCT FROM N.TYPE 
  AND T.MODEL_ID IS NOT DISTINCT FROM N.MODEL_ID 
  AND T.FREQ     IS NOT DISTINCT FROM N.FREQ;

另一个更简单的选项是使用 INTERSECT 集合运算符:

SELECT * FROM t1
INTERSECT
SELECT * FROM T2;

db<>fiddle demo

多一个选项:

SELECT *  
FROM T1 AS T, T2 AS N 
WHERE EQUAL_NULL(T.ID,N.ID)
  AND EQUAL_NULL(T.TYPE,N.TYPE)
  AND EQUAL_NULL(T.MODEL_ID,N.MODEL_ID)
  AND EQUAL_NULL(T.FREQ,N.FREQ);