【问题标题】:Updating PostgreSQL JSONB key value by adding 1 to existing key value通过将 1 添加到现有键值来更新 PostgreSQL JSONB 键值
【发布时间】:2017-04-10 16:55:08
【问题描述】:

更新 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);

但上面一个给出错误“无法将jsonb转换为int”

我的预期输出是

{
    "id": 1,
    "value": 101
}

【问题讨论】:

  • 请发布testTable的表架构
  • testTable 仅包含一列 jsondata 类型 JSONB
  • postgresql 不应该报告 "cannot convert jsonb to int" 然后

标签: postgresql postgresql-9.5


【解决方案1】:

看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)
  )
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 2022-01-04
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2014-01-10
    相关资源
    最近更新 更多