我需要从jsonb类型列中删除一些值。
jsonb值
{"services": [59, 61], "locations": ["34"]}
此查询无效。
select jsonb_set(data, '{services}', (data->'services') - 59) from employees
WHERE data @> '{"services":[59]}';
但是,这可行:
select jsonb_set(data, '{locations}', (data->'locations') - '34') from
employees WHERE data @> '{"services":[59]}';
如何在没有键索引和单引号的情况下从59
中删除services
?
答案 0 :(得分:0)
(数据->'服务')-59
按索引删除项目
示例
/* - 3 is the index to be deleted in a NUMERIC array 0 14 1 15 2 16 3 17 * to be deleted 4 18 */ select '[14, 15, 16, 17, 18]'::jsonb - 3
| ?column? | | :--------------- | | [14, 15, 16, 18] |
文本元素数组
CREATE TABLE employees ( id serial primary key, data jsonb );
✓
insert into employees(data) values ('{"services": [50, 57, 59, 61], "locations": ["34"]}'::jsonb), ('{"services": [19, 21], "locations": ["34"]}'::jsonb) ;
2 rows affected
-- The link was used (https://dba.stackexchange.com/questions/54283/how-to-turn-json-array-into-postgres-array) select employees.id, jsonb_set(data, '{services}', ('[' || string_agg('"' || elem::text || '"' ,' ,') || ']')::jsonb - '59') from employees, json_array_elements((data->'services')::json) elem WHERE data @> '{"services":[59]}' group by employees.id ;
id | jsonb_set -: | :---------------------------------------------------- 1 | {"services": ["50", "57", "61"], "locations": ["34"]}
db <>提琴here