1. 程式人生 > >PostgreSQL的jsonb型別中包含陣列的 增加、遍歷、查詢、修改

PostgreSQL的jsonb型別中包含陣列的 增加、遍歷、查詢、修改

Postgresql 版本 :9.5

表結構

CREATE TABLE person(id serial, info jsonb);

JSONB結構

[{"num":"學號","name":"姓名","score":"成績"}, {"num":"學號","name":"姓名","score":"成績"}]

插入

INSERT INTO person (info) VALUES ('[{"num":"1","name":"張三","score":"90"}]'::jsonb);

增加

UPDATE person SET info = info || '[{"num":"2","name":"李四","score":"91"}]
'::jsonb;

遍歷

SELECT t.* FROM person, jsonb_to_record(info) AS t(num text, name text, score text) WHERE person.id=1;

CREATE TABLE rt_person_info(no text, name text, score text);

SELECT t.* FROM person, jsonb_populate_recordset(null::rt_person_info, info) WHERE person.id=1;

查詢

SELECT * FROM person WHERE info @>
'[{"num":"1"}]'::jsonb;

修改

UPDATE person t1 SET info = jsonb_set(info, array[(SELECT ORDINALITY::INT - 1 FROM person t2, jsonb_array_elements(info) WITH 
ORDINALITY WHERE t1.id = t2.id AND value->>'num' = '1')::text, 'score'::text], '"92"') WHERE id = '1'