![](/img/trans.png)
[英]How to extract values from array json column into multiple rows in Postgresql?
[英]Postgresql - Extract values from json from [] values
在 postgresql 中,我試圖查詢一個視圖,其中一個名為codeids
列是codeids
類型,看起來像這樣 - ["Code-oyg0vYNpL", "Code-m9db_s", "Code89nb"]
。 我想查詢這一列,結果每行返回一個值。 在上面的例子中,查詢應該返回 3 行。
我已經使用json_array_elements
和jsonb_array_length
對完全形成的 json blob 運行查詢以提取部分 json 結構。 但是有人這個更簡單的 json 結構讓我感到困惑,因為我無法找出用於提取這三個值的 postgresql 語句的正確格式。 提前致謝。
SELECT
role -> 'title' AS team_role,
jsonb_array_length(role -> 'names') AS member_count
FROM jsonb_array_elements(value -> 'team') AS team(role)
你快到了……但是你需要在查詢中引入實際的表(或視圖)。 我發現LATERAL JOIN
語法在這里更明顯:
SELECT
t.role -> 'title' AS team_role,
jsonb_array_length(t.role -> 'names') AS member_count
FROM myview v
CROSS JOIN LATERAL jsonb_array_elements(v.codeids -> 'team') AS t(role)
編輯:如果您將 jsonb 數組存儲在表列中,那就更簡單了:
create table test_table (codeids jsonb);
insert into test_table(codeids) values ('["Code-oyg0vYNpL", "Code-m9db_s", "Code89nb"]');
select x.role
from test_table t
cross join lateral jsonb_array_elements(t.codeids) x(role);
| role |
| -------------- |
| Code-oyg0vYNpL |
| Code-m9db_s |
| Code89nb |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.