我正在嘗試將 ARRAY 添加到現有的 jsonb ARRAY。此陣列將添加到現有陣列的 ARRAY[0] 中。當我對細節進行硬編碼時,它可以正常作業,但是當我嘗試動態執行它時,它會因上述錯誤而失敗。我究竟做錯了什么?
Postgresql 13 資料庫服務器版本
with whatposition as (select position pos from users cross join lateral
jsonb_array_elements(user_details->'Profile') with ordinality arr(elem,position)
where display_ok=false)
update users set user_details=jsonb_set(
user_details,concat('ARRAY[''userProfile'',''',(select pos-1 from whatposition)::text,'''',',''DocumentDetails'']')::text[],
'[{"y":"supernewValue"}]')
where display_ok=false;
SQL 錯誤 [22P02]:錯誤:格式錯誤的陣列文字:“ARRAY['userProfile','0','DocumentDetails']”詳細資訊:陣列值必須以“{”或維度資訊開頭。
這是 with 子查詢輸出。
with whatposition as (select position pos from users cross join lateral
jsonb_array_elements(user_details->'userProfile') with ordinality arr(elem,position)
where display_ok=false)
select concat('ARRAY[''userProfile'',''',(select pos-1 from whatposition)::text,'''',',''DocumentDetails'']');
以上 SQL 的輸出
ARRAY['userProfile','0','DocumentDetails']
但是當我將值作為文字傳遞給上述 SQL 時,它作業得很好。
with whatposition as (select position pos from users cross join lateral
jsonb_array_elements(user_details->'userProfile') with ordinality arr(elem,position)
where display_ok=false)
update users set user_details=jsonb_set(
user_details,ARRAY['userProfile','0','DocumentDetails'],'[{"y":"cccValue"}]')
where display_ok=false;
uj5u.com熱心網友回復:
您不應該將ARRAY[…]語法放在文字值中。
with whatposition as (
select position pos
from users
cross join lateral jsonb_array_elements(user_details->'Profile') with ordinality arr(elem,position)
where display_ok=false
)
update users
set user_details=jsonb_set(
user_details,
ARRAY['userProfile', (select pos-1 from whatposition)::text, 'DocumentDetails'],
'[{"y":"supernewValue"}]'
)
where display_ok=false;
uj5u.com熱心網友回復:
您嘗試的查詢超出了表面語法錯誤(由 Bergi 解決)。
如果 CTE 回傳多行(如預期),則 ARRAY 建構式將失敗,因為嵌套的子選擇只允許在此位置回傳單個值。
您似乎想將該屬性添加"DocumentDetails": [{"y": "cccValue"}]}到嵌套 JSON 陣列的每個元素中user_details->'userProfile'。如果是這樣,請改用此查詢:
UPDATE users
SET user_details
= jsonb_set(user_details
, '{userProfile}'
, (SELECT jsonb_agg(value || '{"DocumentDetails": [{"y":"cccValue"}]}')
FROM jsonb_array_elements(user_details -> 'userProfile') ja
)
)
WHERE display_ok = FALSE;
db<>在這里小提琴
相關子查詢取消嵌套陣列,將屬性添加到每個元素物件(如果已經存在,則更新它,并將陣列聚合回來。
jsonb_set()然后用更新的陣列替換舊的嵌套陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343254.html
標籤:PostgreSQL jsonb
