sql - 结合大小写不同

标签 sql postgresql

我在学习合并时感到困惑,我是 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?

最佳答案

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

Documentation Postgresql 中的定义

The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null.

所以这意味着它会返回第一个参数not null,它不像case语句那样有true

让我们举个例子:

select coalesce(null, 1)

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

select coalesce(null, null, 1)

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

select coalesce(null, 1, 2)

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

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

Demo<>Fiddle

希望对你有帮助

关于sql - 结合大小写不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52959235/

相关文章:

python - 无法在 Python 中使用 pscopg2 库创建架构

hibernate - Spring + Hibernate + Postgresql readOnly Transaction,按需保存

sql - rs.filter 属性的使用无效?

php - 如何在 laravel 函数中添加 php 变量

postgresql - Postgres Slaves/Read Replicas 的 Scala Slick 配置

postgresql - 更改序列的起始值 - Postgresql

postgresql - 如果 x 列上的用户记录不为空,我如何计算该用户在第一次不为空后有多少条记录?

mysql - 更新更新触发器中的其他行

php - 如何创建一个新列包含 id 列的散列

sql - 查询结果太多