[英]How to UNNEST an Array Postgresql double nested?
我正在努力以這種格式取消嵌套數組 - >順便說一句新手警報! 用例:我想計算一個表中的所有 v=1234 custom_fields = {f=[{v=1234}, {v=[]}]}
我嘗試使用:
select custom_fields[safe_offset(1)]
from database
limit 10
它給了我列,但仍然是嵌套的。
然后我試過這個:
SELECT tickets.id, cf
FROM db.tickets
CROSS JOIN UNNEST(tickets.custom_fields) AS cf
limit 10
與第一個代碼相同的行為。
我試過這個[][]:
SELECT
custom_fields[1][1]
FROM db.tickets
limit 10
*Array element access with array[position] is not supported. Use
array[OFFSET(zero_based_offset)] or array[ORDINAL(one_based_ordinal)]
但 jeah 這就是這條消息開頭的查詢。
我很迷茫..有什么想法嗎?
不確定我是否完全理解您的問題,但我復制了您的示例,添加了一個id
列和包含 json 的json_col
。 以下語句提取不同行中的每個v
值,並且仍然與id
相關
with my_tbl as (
select 1 id, '{"f":[{"v":1234}, {"v":2345}, {"v":7777}]}'::jsonb as json_col UNION ALL
select 2 id, '{"f":[{"v":6789}, {"v":3333}]}'::jsonb as json_col
)
select * from my_tbl, jsonb_to_recordset(jsonb_extract_path(json_col, 'f')) as x(v int);
該 sql 使用JSONB_EXTRACT_PATH
提取f
部分,並使用JSONB_TO_RECORDSET
為每個v
值創建一行。 文檔中有關JSON 函數的更多信息
id | json_col | v
----+------------------------------------------------+------
1 | {"f": [{"v": 1234}, {"v": 2345}, {"v": 7777}]} | 1234
1 | {"f": [{"v": 1234}, {"v": 2345}, {"v": 7777}]} | 2345
1 | {"f": [{"v": 1234}, {"v": 2345}, {"v": 7777}]} | 7777
2 | {"f": [{"v": 6789}, {"v": 3333}]} | 6789
2 | {"f": [{"v": 6789}, {"v": 3333}]} | 3333
(5 rows)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.