sql - PostgreSQL concating multiple cases 结果为 null

标签 sql postgresql

我是 PostgreSQL 的新手。下一个查询在 Oracle 中有效,但在 PSQL 中无效:

select case 1 when null then null else 1||' ' end ||
       case 2 when null then null else 2||' ' end ||
       case 3 when null then null else 3 end as total
from   numbers

如果1和2不为空,只有3为空,则尽管1和2不为空,total的结果不应该为null,但total的结果仍为null。

最终的结果应该是当3列其中一列不为null时,total不应该为null。这可能吗?

最佳答案

对于 Postgres - 与 Oracle 不同 - 空字符串 ''null 是两个不同的东西。在 Oracle 中,与 null 的字符串连接将 null 值视为空字符串。但是,当您在 Oracle 中存储空字符串 ('') 时,它会将其视为 null 值。

在 SQL 中,所有(或几乎所有)运算符都被定义为如果任何参数为 null,则结果也为 null,例如42 + null'foo'||null

此外,case 1 when null 也没有意义。 1 永远不会是 null,因此永远不会执行 when 部分。此外,您不能以这种方式测试 null。您需要使用 is null 但您不能使用缩写的 case 语法。

你可能打算写这样的东西:

select case when first_column is null then '' else first_column||' ' end ||
       case when second_column is null then '' else second_column||' ' end ||
       case when third_column is null null then '' else third_column end as total
from   numbers

然而,您可以使用 coalesce() 使这变得容易得多:

select coalesce(first_column, '')||' '||coalesce(second_column, '')||' '||coalesce(third_column, '')

或使用将 null 视为空字符串的 concat():

select concat(first_column, ' ', second_column, ' ', third_column)

或者更简单地使用 concat_ws() “concat with separator”:

select concat_ws(' ', first_column, second_column, third_column)

concat_ws() 会将分隔符(第一个参数)放在其他参数的每个值之间,但会正确处理 null 值和空字符串,以便分隔符不会在两个值之间出现两次。

concat('one', ' ', null, ' ', '') 返回 'one '
但是 concat_ws(' ', 'one', null, '') 将返回 'one'

关于sql - PostgreSQL concating multiple cases 结果为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46323538/

相关文章:

SQL 服务器 : need to add a primary key

postgresql - 如何重新启动我的 openshift postgres 墨盒?

postgresql - 在客户端代码的目录 header 中使用定义的基本类型 OID 是否安全?

postgresql - 如何从包含 "CASE WHEN"语句的 Postgresql 查询中检索数据?

postgresql - 在 Postgres 中更改分区表的表空间

sql - Postgresql根据条件选择行窗口

sql - Django 模型 - 外键作为主键

c# - 使用来自两个数据库的自动增量ID连接来自两个表的数据

sql - 在SQL Server中,如何获取多列日期的最新日期?

mysql - 按 max() 其他列显示列