LEFT JOIN ON NULL 键值结合 GROUP BY

LEFT JOIN ON NULL Key Values Combined with GROUP BY

我正在使用 Teradata SQL 并编写了以下查询(注意 LEFT JOIN)

SELECT
    key1,
    secondvalue,
    count(DISTINCT firstvalue)
FROM
(
    SELECT
        t1.val AS firstvalue,
        t1.key1,
        t2.val AS secondvalue
        
    FROM table1 t1
    LEFT JOIN table2 t2 ON t1.key1 = t1.key1 AND t1.key2 = t2.key2 AND t1.key3 = t2.key3
) AS Testcase
GROUP BY 1, 2

t1.key2 和 t1.key3(左侧 table)的一些条目为 NULL。在这种情况下,结果中没有显示行,为什么? Teradata 是特定的吗,我希望 LEFT JOIN 显示具有 NULL 值的行。

例如,如果我选择将 LEFT JOIN 语句缩减为

SELECT
    key1,
    secondvalue,
    count(DISTINCT firstvalue)
FROM
(
    SELECT
        t1.val AS firstvalue,
        t1.key1,
        t2.val AS secondvalue
        
    FROM table1 t1
    LEFT JOIN table2 t2 ON t1.key1 = t1.key1
) AS Testcase
GROUP BY 1, 2

出现了更多不同的 key1 值,这不应该是这样,对吧?我想查看 key1 的所有不同值,即使 key2 和 key3 为 NULL。如果没有,我想从第二个table.

看具体值

我真的不想先将 NULL 值映射到另一个值。

Some entries for t1.key2 und t1.key3 (of the left sided table) are NULL. When that's the case, the rows are not showing in the result, why?

可能是因为 group bydistinct 会将所有空值组合在一起。确实SQL中null不一定等于null,但我认为从distinct和group by的角度来看,nulls算是等价的[=30] =]

I would expect a LEFT JOIN to show rows with NULL values.

我从未尝试过左侧为 null 的左外连接。我不能说联接是否会为这样的行发出结果,但我可以告诉你它不会匹配等值联接,因为 null 不等于 null。您在寻找完整的外部联接吗?

LEFT JOIN table2 t2 ON t1.key1 = t1.key1

这个谓词会匹配t1.key1 is not null所在的每一行,这几乎是笛卡尔积。这就是为什么你的计数要大得多。

我想你想要

LEFT JOIN table2 t2 ON t1.key1 = t2.key1

I'd want to see all distinct values for key1, even when then key2 and key3 are NULL

总的来说,我觉得你想要的是

LEFT JOIN table2 t2 ON t1.key1 = t2.key1 AND coalesce(t1.key2, -1) = coalesce(t2.key2, -1) AND coalesce(t1.key3, -1) = coalesce(t2.key3, -1)

您希望 coalesce 的第二个参数是 key2key3 的任何类型的语法有效值,但该值在您的使用中无效它(否则,我们将连接一侧有 -1 和另一侧有 null 的行。