【问题标题】:How to return 0 instead of NULL in postgresql?如何在 postgresql 中返回 0 而不是 NULL?
【发布时间】:2019-01-24 15:03:26
【问题描述】:

我在连接两个表的内容时遇到了一些问题。我想要结果中的 0 而不是 NULL 。 这是目前的情况:

表1

Name    v1       v2
A       1         2
B       5         3
C       8         4

表2

Name    v3       v4    Id
B       8        12    1
B       7        22    3
C       6         4    2

结果

Name    v3       v4 
A       NULL     NULL
B       8        12
C       NULL     NULL

预期结果

Name    v3       v4 
A        0        0
B        8       12
C        0        0

我尝试了以下方法来实现结果:

select t1.Name,
    (select coalesce(v3,0) from table2 where Name = t1.Name and id =1),    
    (select coalesce(v4,0) from table2 where Name= t1.Name and id =1)
from table1 t1

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    你必须在子查询之外使用coalesce

    select t1.Name,
           coalesce((select v3 from table2 where Name= t1.Name and id = 1), 0),
           coalesce((select v4 from table2 where Name= t1.Name and id = 1), 0)
      from table1 t1
    

    或者更好的是,使用左连接而不是相关子查询(值列表中的相关子查询在比小表更大的情况下应该非常慢)。

    select t1.name, coalesce(t2.v3, 0), coalesce(t2.v4, 0)
      from table1 t1 
           left join table2 t2 on t1.name = t2.name and t2.id = 1;
    

    【讨论】:

    • 为了解释原因,子查询在table1 的每一行上运行,并使用返回的行来填充值。当t1.nameAC 时,select ... from table2 where Name = t1.Name and id =1 不返回任何行,因此coalesce 甚至没有机会运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 2021-04-25
    • 2011-12-19
    • 2021-03-10
    • 2010-11-05
    相关资源
    最近更新 更多