【问题标题】:Use jsonb structure in postgresql在 postgresql 中使用 jsonb 结构
【发布时间】:2021-08-14 20:47:35
【问题描述】:

我有一张桌子emp3

```
   - id int not null
   - lvl varchar
   - includes jsonb
```

表结构:

id lvl inculdes
1 jj~ii null
2 jj~ii~aa null
3 ii null

我想根据 lvl 列通过拆分“~”来​​更新包含列。我可以这样做:

```
       do $$declare 
          i record;
          tbl_var jsonb := null;
          tbl_var1 text[];
          part varchar;
            begin
              for i in select * from emp3 where includes is null
               loop 
                 if array_length(string_to_array(i.lvl, '~'), 1) is not null then 
                 tbl_var1 := null;
                  foreach part in array string_to_array(i.lvl, '~')
                   loop
                    tbl_var1 := concat(tbl_var1, '{"lvls" : "',part,'"}');
                      UPDATE emp3 set includes = tbl_var1 where id = i.id;
                   end loop;
                else
                 tbl_var := i.lvl;
                 UPDATE emp3 set includes = tbl_var where id = i.id;
                end if;
              end loop;
             end $$;
```

执行查询后的输出:

id lvl inculdes
1 a~b ["{"lvls" : "a"}", "{"lvls" : "b"}"]
2 a~b~c ["{"lvls" : "a"}", "{"lvls" : "b"}","{"lvls" : \c"}"]
3 a ["{"lvls" : "a"}"]

但我想以这种格式输出:

id lvl inculdes
1 a~b [{"lvls" : "a"}, {"lvls" : "b"}]
2 a~b~c [{"lvls" : "a"}, {"lvls" : "b"},{"lvls" : "c"}]
3 a [{"lvls" : "a"}]

没有转义字符并且 " 不附加在 dict 的开头和结尾。 这是如何实现的

【问题讨论】:

  • 对不起,我不知道如何正确格式化问题,如果有人知道请这样做,以便问题结构良好(表 n 代码)
  • 我删除了不支持的 Postgres 版本(9.1、9.3)的标签,因为它们都不支持jsonb
  • 感谢@a_horse_with_no_name

标签: sql arrays json postgresql jsonb


【解决方案1】:

使用jsonb_build_object解决了这个问题:

array_append(tbl_var1, jsonb_build_object('lvls',part));

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 2020-11-18
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2019-09-05
    • 2017-10-07
    • 2020-12-08
    • 2021-12-12
    相关资源
    最近更新 更多