通过向现有键值加 1 来更新 PostgreSQL JSONB 键值
Updating PostgreSQL JSONB key value by adding 1 to existing key value
我在更新 JSON 数据时遇到错误
CREATE TABLE testTable
AS
SELECT $${
"id": 1,
"value": 100
}$$::jsonb AS jsondata;
我想通过加 1 将 value
更新为 101,在访问了很多网站后我发现了这个说法
UPDATE testTable
SET jsondata = JSONB_SET(jsondata, '{value}', (jsondata->>'value')::int + 1);
但上面一个给出了错误"cannot convert jsonb to int"
我的预期输出是
{
"id": 1,
"value": 101
}
查看jsonb_set的签名(使用\df jsonb_set
)
Schema | Name | Result data type | Argument data types | Type
------------+-----------+------------------+----------------------------------------------------------------------------------------+--------
pg_catalog | jsonb_set | jsonb | jsonb_in jsonb, path text[], replacement jsonb, create_if_missing boolean DEFAULT true | normal
你要的是这个..
UPDATE testTable
SET jsondata = jsonb_set(
jsondata,
ARRAY['value'],
to_jsonb((jsondata->>'value')::int + 1)
)
;
我在更新 JSON 数据时遇到错误
CREATE TABLE testTable
AS
SELECT $${
"id": 1,
"value": 100
}$$::jsonb AS jsondata;
我想通过加 1 将 value
更新为 101,在访问了很多网站后我发现了这个说法
UPDATE testTable
SET jsondata = JSONB_SET(jsondata, '{value}', (jsondata->>'value')::int + 1);
但上面一个给出了错误"cannot convert jsonb to int"
我的预期输出是
{
"id": 1,
"value": 101
}
查看jsonb_set的签名(使用\df jsonb_set
)
Schema | Name | Result data type | Argument data types | Type
------------+-----------+------------------+----------------------------------------------------------------------------------------+--------
pg_catalog | jsonb_set | jsonb | jsonb_in jsonb, path text[], replacement jsonb, create_if_missing boolean DEFAULT true | normal
你要的是这个..
UPDATE testTable
SET jsondata = jsonb_set(
jsondata,
ARRAY['value'],
to_jsonb((jsondata->>'value')::int + 1)
)
;