2016-07-15 100 views
0

我有orders一個表:JSON陣列內變化JSON對象值

postgres=# \d orders 
           Table "public.orders" 
     Column  |   Type    |    Modifiers 
--------------------+-----------------------------+------------------------------------- 
id     | uuid      | not null default uuid_generate_v4() 
production_details | jsonb      | 

production_details我被表示爲如下:

postgres=# SELECT production_details FROM orders; 
{ 
    "data":[ 
     { 
     "id":"1a24586c-c917-45d0-93d9-2d969fa6959d", 
     "quantity":10, 
     "production_at":"2016-04-17T00:00:00.000+00:00" 
     }, 
     ... 
    ] 
} 

並且對於每個production_detail我想改變timestamp到只是date

我知道我可以選擇所有production_at爲:

SELECT (jsonb_array_elements(production_details->'data')->>'production_at') FROM orders; 

然而,如何及時更新這些JSON?

回答

0

解壓數組,編輯元素並重新構建整個對象。

示例數據:

create table orders (id int, details jsonb); 
insert into orders values (1, 
'{ 
    "data":[ 
     { 
     "id":"1a24586c-c917-45d0-93d9-2d969fa6959d", 
     "quantity":10, 
     "production_at":"2016-04-17T00:00:00.000+00:00" 
     }, 
     { 
     "id":"1a24586c-c917-45d0-93d9-2d969fa6959x", 
     "quantity":20, 
     "production_at":"2016-04-18T00:00:00.000+00:00" 
     } 
    ] 
}'); 

查詢:

update orders o 
set details = (
    select 
     json_build_object(
      'data', 
      jsonb_agg(
       jsonb_set(
        e, 
        '{production_at}', 
        to_jsonb((e->>'production_at')::timestamp::date::text)) 
       ) 
      ) 
    from orders, jsonb_array_elements(details->'data') e 
    where id = o.id 
    ); 

結果:

select id, jsonb_pretty(details) from orders; 

id |      jsonb_pretty       
----+----------------------------------------------------------- 
    1 | {              + 
    |  "data": [           + 
    |   {            + 
    |    "id": "1a24586c-c917-45d0-93d9-2d969fa6959d",+ 
    |    "quantity": 10,        + 
    |    "production_at": "2016-04-17"    + 
    |   },            + 
    |   {            + 
    |    "id": "1a24586c-c917-45d0-93d9-2d969fa6959x",+ 
    |    "quantity": 20,        + 
    |    "production_at": "2016-04-18"    + 
    |   }            + 
    |  ]             + 
    | } 
(1 row) 
+0

如果我想更新的所有訂單,而無需指定一個特定的ID?因爲當我刪除'WHERE'子句時,內部'SELECT'選擇所有的命令。 – squixy

+1

我已經編輯了答案。查詢現在更新所有行。 – klin