PostgreSQL从JSONB字段中的对象数组获取密钥

时间:2019-05-07 06:49:47

标签: postgresql jsonb postgresql-json

这是jsonb列的伪数据

[ { "name": [ "sun11", "sun12" ], "alignment": "center", "more": "fields" }, { "name": [ "sun12", "sun13" ], "alignment": "center" }, { "name": [ "sun14", "sun15" ] }]

我想从对象的jsonb数组中获取所有名称键值...期望输出-

[ [ "sun11", "sun12" ], [ "sun12", "sun13" ], [ "sun14", "sun15" ] ]

问题是我可以通过给索引提供0、1等来获取名称键值

SELECT data->0->'name' FROM public."user";
[ "sun11", "sun12" ]

但是我无法从同一对象数组中获取所有名称键值。我只想从json对象数组中获取所有键值。任何帮助都会有所帮助。谢谢

2 个答案:

答案 0 :(得分:1)

demo:db<>fiddle(首先是最终查询,下面是中间步骤)

WITH data AS (
    SELECT '[ { "name": [ "sun11", "sun12" ], "alignment": "center", "more": "fields" }, { "name": [ "sun12", "sun13" ], "alignment": "center" }, { "name": [ "sun14", "sun15" ] }]'::jsonb AS jsondata
)
SELECT 
    jsonb_agg(elems.value -> 'name')    -- 2
FROM 
    data,
    jsonb_array_elements(jsondata) AS elems -- 1
  1. j sonb_array_elements()将每个数组元素扩展为一行
  2. ->运算符给出属性名称的数组;之后,jsonb_agg()将所有提取的数组重新放入一个。

答案 1 :(得分:0)

我的例子

SELECT DISTINCT sub.name FROM (

SELECT
jsonb_build_object('name', p.data->'name') AS name
FROM user AS u
WHERE u.data IS NOT NULL
) sub
WHERE sub.name != '{"name": null}';