2016-08-03 77 views
0

我有问题,更新的postgree jsonb类型,PostgreeSQL查询ň操纵JSON数据

这是我的例子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格式。 任何帮助将不胜感激。

谢谢

+0

[考虑标准化数据(https://www.google.com.br/search?q=database+normalization&ie=utf-8&oe=utf-8&gws_rd=cr&ei= xduhV_r9H8SFwgT65KyIDA) –

回答

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%'; 
+0

感谢您的回答,但是当我运行脚本时出现这样的错误, “错误:列”s.produk“必须出现在GROUP BY子句中或用于聚合函数中 LINE 3:select json_build_object('total',produk#>>'{total}','produc ...“... 我尝试在内部查询”select data ...“中添加”group by s.produk“ ,它的工作, 我希望这一点s是正确的,但如果您对此错误有任何意见,请再次通知我..再次感谢.. – sedayux