PostgreSQL 从 jsonb 对象中获取任何值

PostgreSQL get any value from jsonb object

我想获取任一键 'a' 或 'b' 的值(如果其中一个存在)。如果两者都不存在,我想要映射中任何键的值。

示例:

目前我是这样做的: SELECT COALESCE(o ->> 'a', o ->> 'b', o->> 'c') FROM...

问题是我真的不想明确命名键 'c',因为有些对象可以有任何键。

那么如何达到"Get value of either 'a' or 'b' if either exists. If neither exists, grab anything that exists."想要的效果呢?

我正在使用 postgres 9.6。

可能太长了:

t=# with c(j) as (values('{"a": "aaa", "b": "bbbb", "c": "cccc"}'::jsonb))
, m as (select j,jsonb_object_keys(j) k from c)
, f as (select * from m where k not in ('a','b') limit 1)
t-# select COALESCE(j ->> 'a', j ->> 'b', j->>k) from f;
 coalesce
----------
 aaa
(1 row)

并且没有 a,b 键:

t=# with c(j) as (values('{"a1": "aaa", "b1": "bbbb", "c": "cccc"}'::jsonb))
, m as (select j,jsonb_object_keys(j) k from c)
, f as (select * from m where k not in ('a','b') limit 1)
select COALESCE(j ->> 'a', j ->> 'b', j->>k) from f;
 coalesce
----------
 cccc
(1 row)

想法是 extract all keys with jsonb_object_keys 得到第一个 "random"(因为我什么都不点) (limit 1) 然后用在最后一个coalesce不变