在 postgresql 中添加列 JSON
Add column in postgresql JSON
我正在使用 postgresql 9.4
我在 table 中有一个 json 列,它包含以下值:
"{
"title" : "risk",
"name" : "David"
}"
我必须执行两个功能
- 更新名称值到"John"
- 插入 "city" : "paris"
我的最终值应该在我的 table 列中
"{
"title" : "risk",
"name" : "John",
"city" : "paris"
}"
基本上,我想更新和插入此 json 列的查询,但我无法将数据库更改为更高版本
像:
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")
在 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() as x full join json_each() 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 后,只需从数据库脚本中删除函数和运算符声明,其他任何内容都不应更改。
我正在使用 postgresql 9.4
我在 table 中有一个 json 列,它包含以下值:
"{
"title" : "risk",
"name" : "David"
}"
我必须执行两个功能
- 更新名称值到"John"
- 插入 "city" : "paris"
我的最终值应该在我的 table 列中
"{
"title" : "risk",
"name" : "John",
"city" : "paris"
}"
基本上,我想更新和插入此 json 列的查询,但我无法将数据库更改为更高版本
像:
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")
在 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() as x full join json_each() 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 后,只需从数据库脚本中删除函数和运算符声明,其他任何内容都不应更改。