【问题标题】:Add column in postgresql JSON在 postgresql JSON 中添加列
【发布时间】:2017-11-10 10:31:35
【问题描述】:

我正在使用 postgresql 9.4

我在表中有一个 json 列,它包含值:

"{
  "title" : "risk",
  "name"  : "David"
}"

我必须执行两个功能

  1. 更新名称值为“John”
  2. 插入 “城市”:“巴黎”

我的最终值应该在我的表格列中

"{
  "title" : "risk",
  "name"  : "John",
  "city"  : "paris"
}"

基本上,我想更新和插入此 json 列的查询,我无法将数据库更改为更高版本

【问题讨论】:

  • 嗨。请阅读How to Ask。请解释文档如何没有告诉您这一点。

标签: sql json postgresql postgresql-9.4


【解决方案1】:

类似:

update table 
set jbcolumn = json_build_object('title',jbcolumn->>'title','name','John','city','Paris') where bcolumn->>'name' = 'David

在 postgres 9.4 中

https://www.postgresql.org/docs/9.4/static/functions-json.html

json_build_object(VARIADIC "any")

【讨论】:

  • 我已经尝试过了,但是出现错误:函数 json_build_object(unknown, unknown, unknown, unknown, unknown, unknown) 不存在
  • 这对我有所帮助,但需要更新一点
【解决方案2】:

在 PostgreSQL 的更高版本中,有一个有用的 || 运算符用于 JSON 类型。对于 9.4 版本,您可以自己创建它:

create function my_json_cat(json, json) returns json stable strict language sql as $$
  select json_object_agg(coalesce(x.key, y.key), coalesce(y.value, x.value))
  from json_each($1) as x full join json_each($2) as y on (x.key = y.key)
$$;

create operator || (
  leftarg=json, rightarg=json,
  procedure=my_json_cat);


with t(x,y) as (values('{
  "title" : "risk",
  "name"  : "David"
}'::json, '{
  "title" : "risk",
  "name"  : "John",
  "city"  : "paris"
}'::json))
select x || y from t;

所以你的最后陈述可能是

update your_table set
  your_column = your_column || '{"name": "John", "city": "paris"}'
where ...

升级到更高版本的 PostgreSQL 后,只需从数据库脚本中删除函数和运算符声明,其他任何内容都不应更改。

Demo.

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多