【问题标题】:Postgresql update json data propertyPostgresql 更新 json 数据属性
【发布时间】:2018-05-07 08:27:14
【问题描述】:

我创建了一个字段名称是结果,类型是文本。我只想更新列中的“纬度”。当我使用这个查询时,我得到语法错误。我能怎么做?

列数据是

"{"lat":"48.00855","lng":"58.97342","referer":"https:\/\/abc.com\/index.php"}"

查询是

update public.log set (result::json)->>'lat'=123 where id=6848202

语法错误是

ERROR:  syntax error at or near "::"

【问题讨论】:

  • Postgres 版本?
  • Postgres 版本为 9.6
  • 对我们如何在 postgres 9.4 中实现这一点有任何想法吗?

标签: json postgresql jsonb postgresql-9.4 postgresql-9.6


【解决方案1】:

使用jsonb concatenation operatorPostgres 9.5+):

update log
set result = result::jsonb || '{"lat":"123"}'
where id = 6848202

Postgres 9.4 中使用 json_each()json_object_agg()(因为 jsonb_object_agg() 在 9.4 中不存在)。

update log
set result = (
    select json_object_agg(key, case key when 'lat' then '123' else value end)
    from json_each(result)
    )
where id = 6848202

两种解决方案都假定 json 列不为空。如果它不包含 lat 键,第一个查询将创建它,但第二个不会。

【讨论】:

  • 如果有人想知道如何处理来自现有列的数据,你们都可以利用json_build_object 函数来执行此操作。 result::jsonb || json_build_object('key', column)
【解决方案2】:

如果该列仍然为空,您可以使用coalesce。答案在这里提供:PostgreSQL 9.5 - update doesn't work when merging NULL with JSON

【讨论】:

    【解决方案3】:

    我也尝试更新 json 类型字段中的 json 值,但找不到合适的示例。所以我使用 PgAdmin4 连接到 postgres DB,打开所需的表并更改所需字段的值,然后查看 Query History 以查看它使用什么命令来更改它。

    所以,最后,我得到了下一个简单的 python 代码,用于更新 postgres db 中的 json 字段:

    import psycopg2
    
    conn = psycopg2.connect(host='localhost', dbname='mydbname', user='myusername', password='mypass', port='5432')
    cur = conn.cursor()
    cur.execute("UPDATE public.mytable SET options = '{\"credentials\": \"required\", \"users\": [{\"name\": \"user1\", \"type\": \"string\"}]}'::json WHERE id = 8;")
    cur.execute("COMMIT")
    

    【讨论】:

      【解决方案4】:

      在 PostgreSQL 13 中,您可以:

      update public.log set result = jsonb_set(result,'{lat}','"123"') where id=6848202;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-18
        • 1970-01-01
        相关资源
        最近更新 更多