PostgreSQL的COALESCE与多个jsonb_path_query_first一起使用返回null。

huangapple go评论59阅读模式
英文:

PostgreSQL COALESCE with multiple jsonb_path_query_first returns null

问题

You can achieve the desired result by using the COALESCE function along with the jsonb_path_query_first function in PostgreSQL. Here's the translated code:

例如,我有以下查询:

SELECT COALESCE(
   jsonb_path_query_first('{"a": null, "b": "bb"}', '$.a'),
   jsonb_path_query_first('{"a": null, "b": "bb"}', '$.b')
) AS value;

它会返回 null,尽管我使用了 COALESCE。如何在路径 $.a 返回 null 的情况下返回 bb

谢谢。

英文:

For example I have the next query:

SELECT COALESCE(
   jsonb_path_query_first('{"a": null, "b": "bb"}', '$.a'),
   jsonb_path_query_first('{"a": null, "b": "bb"}', '$.b')
) AS value;

it return null although I use COALESCE.

How can I return in the case bb as the path $.a return null?

Thanks

答案1

得分: 2

The problem is, that a "JSON null" is not the same as a "SQL null". One option would be to get rid of all (JSON) null values first:

问题是,"JSON null" 和 "SQL null" 不同。一种解决方法是首先消除所有(JSON)null值:

SELECT COALESCE(
jsonb_path_query_first(jsonb_strip_nulls('{"a": null, "b": "bb"}'), '$.a'),
jsonb_path_query_first('{"a": null, "b": "bb"}', '$.b')
) AS value;

Alternatively make the JSON path return a SQL null by using a condition:

或者,通过使用条件使JSON路径返回SQL null:

SELECT COALESCE(
jsonb_path_query_first('{"a": null, "b": "bb"}', '$ ? (@.a != null).a'),
jsonb_path_query_first('{"a": null, "b": "bb"}', '$.b')
) AS value;

英文:

The problem is, that a "JSON null" is not the same as a "SQL null". One option would be to get rid of all (JSON) null values first:

SELECT COALESCE(
   jsonb_path_query_first(jsonb_strip_nulls('{"a": null, "b": "bb"}'), '$.a'),
   jsonb_path_query_first('{"a": null, "b": "bb"}', '$.b')
) AS value;

Alternatively make the JSON path return a SQL null by using a condition:

SELECT COALESCE(
   jsonb_path_query_first('{"a": null, "b": "bb"}', '$ ? (@.a != null).a'),
   jsonb_path_query_first('{"a": null, "b": "bb"}', '$.b')
) AS value;

huangapple
  • 本文由 发表于 2023年4月13日 21:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定