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'

 

    原文作者:PostgreSQL
    原文地址: https://www.cnblogs.com/23cm/p/5527050.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞