2016-08-03 76 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