postgresql 修改属性
up vote2down votefavorite |
From this article, I tried to update or delete property of a JSONB column: CREATE TABLE xxx (id BIGSERIAL, data JSONB); INSERT INTO xxx(data) VALUES( '{"a":1,"b":2}' ); SELECT * FROM data; id | data ----+------------------ 1 | {"a": 1, "b": 2} create the update function: CREATE FUNCTION jsonb_merge(JSONB, JSONB) RETURNS JSONB AS $$ WITH json_union AS ( SELECT * FROM JSONB_EACH($1) UNION ALL SELECT * FROM JSONB_EACH($2) ) SELECT JSON_OBJECT_AGG(key, value)::JSONB FROM json_union; $$ LANGUAGE SQL; testing: -- replace UPDATE xxx SET data = jsonb_merge(data,'{"b":3}') WHERE id = 1; SELECT * FROM xxx; id | data ----+------------------ 1 | {"a": 1, "b": 3}
-- append UPDATE xxx SET data = jsonb_merge(data,'{"c":4}') WHERE id = 1; SELECT * FROM xxx; id | data ----+------------------------- 1 | {"a": 1, "b": 3, "c": 4} The question is:
. -- remove UPDATE xxx SET data = jsonb_merge(data,'{"b":null}') WHERE id = 1; SELECT * FROM xxx; id | data ----+----------------- 1 | {"a": 1, "c": 4}
|
|||
add a comment |
1 Answer
up vote3down voteaccepted |
Question 1
CREATE FUNCTION jsonb_merge(JSONB, JSONB) RETURNS JSONB AS $$ WITH json_union AS ( SELECT * FROM JSONB_EACH($1) UNION ALL SELECT * FROM JSONB_EACH($2) ) SELECT JSON_OBJECT_AGG(key, value)::JSONB FROM json_union WHERE key NOT IN (SELECT key FROM json_union WHERE value ='null'); $$ LANGUAGE SQL; |