POSTGRES JSON: 更新列中的数组值
POSTGRES JSON: Updating array value in column
我正在使用 POSTGRES SQL JSON.
在 json 列中,值存储为数组,我想使用 SQL 查询
更新它
{"roles": ["Admin"]}
table 列中的输出应为
{"roles": ["SYSTEM_ADMINISTRATOR"]}
我尝试了不同的查询,但没有用。
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', to_jsonb('SYSTEM_ADMINISTRATOR')::jsonb, true);
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', to_jsonb('["SYSTEM_ADMINISTRATOR"]')::jsonb, true);
ERROR: could not determine polymorphic type because input has type unknown
SQL state: 42804
请帮我查询
but at the moment it is to update the value at 0 index
可以使用 jsonb_set()
的基于索引的“路径”来完成
update bo_user
set "json" = jsonb_set("json", '{roles,0}'::text[], '"SYSTEM_ADMINISTRATOR"')
where "json" #>> '{roles,0}' = 'Admin'
“路径”'{roles,0}'
引用数组中的第一个元素,该元素被常量替换 "SYSTEM_ADMINISTRATOR"'
请注意 SQL 字符串文字中的双引号,这是一个有效的 JSON 字符串
WHERE 子句可确保您不会意外更改错误值。
所以这有效。
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', ('["SYSTEM_ADMINISTRATOR"]')::jsonb, true)
where id = '??';
我正在使用 POSTGRES SQL JSON.
在 json 列中,值存储为数组,我想使用 SQL 查询
更新它{"roles": ["Admin"]}
table 列中的输出应为
{"roles": ["SYSTEM_ADMINISTRATOR"]}
我尝试了不同的查询,但没有用。
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', to_jsonb('SYSTEM_ADMINISTRATOR')::jsonb, true);
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', to_jsonb('["SYSTEM_ADMINISTRATOR"]')::jsonb, true);
ERROR: could not determine polymorphic type because input has type unknown
SQL state: 42804
请帮我查询
but at the moment it is to update the value at 0 index
可以使用 jsonb_set()
update bo_user
set "json" = jsonb_set("json", '{roles,0}'::text[], '"SYSTEM_ADMINISTRATOR"')
where "json" #>> '{roles,0}' = 'Admin'
“路径”'{roles,0}'
引用数组中的第一个元素,该元素被常量替换 "SYSTEM_ADMINISTRATOR"'
请注意 SQL 字符串文字中的双引号,这是一个有效的 JSON 字符串
WHERE 子句可确保您不会意外更改错误值。
所以这有效。
UPDATE public.bo_user
SET json = jsonb_set(json, '{roles}', ('["SYSTEM_ADMINISTRATOR"]')::jsonb, true)
where id = '??';