讓我們假設你有一個像數據:
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;
輸出:
至於calculated column
:
- 創建視圖
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?