【问题标题】:Postgres: join if field is not null in both tables?Postgres:如果两个表中的字段都不为空,则加入?
【发布时间】:2018-06-22 00:11:55
【问题描述】:

我想在 Postgres 中加入两个表,但前提是两个字段中的值都不为 NULL。

在我看来像这样的查询实际上已经表现得像这样,没有进一步的条件:

SELECT * FROM aTable a JOIN bTable b on a.value=b.value;

这不会从我的数据库中返回 a.valueb.value 均为 NULL 的行。

但是,我并不完全相信自己了解正在发生的事情。这是因为 NULL 不等于 Postgres 中的 NULL

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    NULL 是一个声明没有值的字段属性。出于这个原因,没有什么是等于NULL,甚至是NULL 本身。如果你想加入NULL,你必须使用函数。

    你可以尝试一些事情:

    -- be sure `escape value` doesn't normally occur in the column to avoid surprises
    on coalesce(a.value, 'escape value') = coalesce(b.value, 'escape value')
    

    -- no need for escape values, but more difficult to read
    on (a.value is null and b.value is null) or a.value = b.value
    

    -- even more text, but intent is more clear (at least to me)
    on case
        when a.value is null and b.value is null then TRUE
        when a.value = b.value then TRUE
        else FALSE
    end
    

    【讨论】:

    • 谢谢!实际上我的情况很好,因为我想在 not null 时加入,但这是一个非常有用的答案,谢谢。
    【解决方案2】:

    NULL 在 Postgres 中不等于 NULL,因此您的条件可以满足您的要求。这是 SQL 数据库中NULL 的定义,因此适用于所有数据库。无论条件是在 where 子句、on 子句、case 表达式还是其他任何地方,这都是正确的。

    如果您希望它们相等,那么您可以在on 子句中使用is not distinct from

    on a.value is not distinct from b.value
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多