PostgreSQL查询n操纵JSON数据

时间:2016-08-03 07:56:19

标签: sql json postgresql nosql

我在postgree中更新jsonb类型有问题,

这是我的例子json

{
  "total": 2, 
  "products":[
        {"name": "guitar", "price": 100000, "brand": "yamaha"},
        {"name": "guitar", "price": 100000, "brand": "kramer"}
   ]
}

这是我的脚本,接着来自here

的回答
update product_map t1
set data = (
    select jsonb_agg(val)
    from (
        select case
            when value->>'brand' = 'yamaha' then jsonb_set(value, '{price}', '3200')
            else value end val
        from product_map t2, jsonb_array_elements(data->'products')
        where t1.merchant = t2.merchant
        and t2.merchant like '0002%'
    ) s
)
where t1.merchant like '0002%';

没有错误,但我的json改为

[
    {"name": "guitar", "price": 3200, "brand": "yamaha"},
    {"name": "guitar", "price": 100000, "brand": "kramer"}
]

我想在这种情况下更新数据是“价格”, 但我不想改变json格式。

1 个答案:

答案 0 :(得分:1)

在您的查询中,您将整个json对象替换为json数组,以便获得此类结果。

请试试这个

 update product_map t1
    set data = (
        select json_build_object('total',data#>>'{total}','products',jsonb_agg(val))
        from (
            select data, 
case when value->>'brand' = 'yamaha' then jsonb_set(value, '{price}', '3200')
                else value end val
            from product_map t2, jsonb_array_elements(data->'products')
            where t1.merchant = t2.merchant
            and t2.merchant like '0002%'
        ) s )where t1.merchant like '0002%';