【问题标题】:Coalesce different with case结合不同的情况
【发布时间】:2018-10-23 23:47:24
【问题描述】:

我对学习合并感到困惑,我是 sql 新手。

示例:

select case when value is null then 1 
    else value end as value 
from table

select coalesce(value, 1)  
from table

在我在互联网上看到的教程中有类似

select coalesce (arg_1, arg_2, arg_3)

如果我做

select coalesce(value, 1, 2)

我怎样才能显示返回值为 2?

【问题讨论】:

  • Postgresql docs 清楚地解释了该函数的工作原理。当您不了解函数的工作原理时,这是一个很好的起点。 The COALESCE function returns the first of its arguments that is not null.
  • Coalesce 返回它匹配的第一个非空值。所以在你的最后一种情况下,1 不为空,所以如果value 为空并且2 永远无法返回,它将被返回。

标签: sql postgresql


【解决方案1】:

您的query 与第一个和第二个将重现相同的结果,但是您对Coalesce 概念的理解是错误的。

Documentation Postgresql中的定义

COALESCE 函数返回它的第一个参数,该参数不是 无效的。只有当所有参数都为 null 时才返回 Null。

所以这意味着它将返回第一个参数not null,它不像case 语句,条件为truefalse

让我们用例子来试试:

select coalesce(null, 1)

它将像您显示的查询一样返回1,或者

select coalesce(null, null, 1)

即使arg_3 中的1 也会返回1,那么not null 中有2 个值怎么样?

select coalesce(null, 1, 2)

它将返回1。为什么?就像在文档中所说的“返回它的第一个不为空的参数”所以当有 2 个值 not null 第一个参数有 not null 值将得到返回

您可以查看此演示并尝试:

Demo<>Fiddle

希望对你有帮助

【讨论】:

  • 简单而伟大的解释,谢谢:)
  • 很乐意提供帮助.. :)
猜你喜欢
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多