我在 PostgreSQL(版本 13.12)表中有一个
json
(不是 jsonb
)列,我想从中删除数组属性的特定值。
例如,在下表 (db-fiddle) 中,我想从
actions
属性中删除所有出现的“D”。
DROP TABLE IF EXISTS test;
CREATE TABLE test (
data JSON
);
INSERT INTO test VALUES
('{"name": "Alice", "actions": ["B", "C", "D"]}'),
('{"name": "Charles", "actions": ["C", "D", "E"]}');
SELECT * FROM test;
我如何通过查询来做到这一点?
select json_build_object('name', name, 'actions', json_agg(action)) as data
from (select data ->> 'name' as name, t.action
from test,
lateral json_array_elements_text(data -> 'actions') t(action)
where action <> 'D') tmp
group by name;
输出:
{“名称”:“爱丽丝”,“动作”:[“B”,“C”]}| {“名称”:“查尔斯”,“行动”:[“C”,“E”]}|