2016-04-05 88 views
1

有沒有方法可以計算JSON中的字段。這裏是我的表是如何設置:PostgreSQL:JSON中的計算字段

CREATE TABLE test1 
(
    id int not null, 
    data JSONB 
) 

這裏是文檔,我將

{ 
    'name': "test name", 
    'age': 46, 
    'heartrate': 211, 
    'heartrateminuseage': function(){ return this.heartrate - this.age; } 
} 

我怎樣才能讓這樣的工作?

回答

1

讓我們假設你有一個像數據:

CREATE TABLE test1(id INT NOT NULL, data JSONB); 

INSERT INTO test1(id, data) 
VALUES (1,'{"name": "test name", 
      "age": 46, 
      "heartrate": 211}'), 
     (2,'{"name": "test name2", 
      "age": 50, 
      "heartrate": 200, 
      "heartrateminuseage": 1000}'); 

要計算"heartrateminuseage",你可以先用提取物值,並使用jsonb_set設置:

SELECT id, data 
    ,jsonb_set(data,'{"heartrateminuseage"}', 
       to_jsonb((data->>'heartrate')::int - (data ->>'age')::int), 
       true) AS data_2 
FROM test1; 

輸出:

enter image description here

至於calculated column

  1. 創建視圖
 
    CREATE VIEW wv_test1 
    AS 
    SELECT id 
     ,jsonb_set(data,'{"heartrateminuseage"}', 
       to_jsonb((data->>'heartrate')::int - (data ->>'age')::int), 
       true) AS data 
    FROM test1; 
  • 創建觸發器,將更新列
  • 創建函數
  • 更多信息:Computed/calculated columns in PostgreSQL and Store common query as column?