我發現了這個問題PostgreSQL: Efficiently split JSON array into rows
我有類似的情況,但是對于插入。考慮到我在 ndjson 檔案中沒有表格但有原始 json ......
{"x": 1}
{"x": 2, "y": 3}
{"x": 8, "z": 3}
{"x": 5, "y": 2, "z": 3}
我想將資料插入表格的表格中(其中沒有列的json欄位存盤在json列中)
| X | 是的 | json |
|---|---|---|
| 1 | 無效的 | 無效的 |
| 2 | 3 | 無效的 |
| 8 | 無效的 | {“z”:3} |
| 5 | 2 | {“z”:3} |
如何定義我的表,以便 postgresql 在插入或復制時自動執行
uj5u.com熱心網友回復:
使用運算子->并將值轉換為現有常規列的值的正確型別。使用洗掉運算子獲取剩余的 JSON 值。
我在示例中使用了 CTE。相反,json_data使用單個 JSONB 列創建表并將 JSON 檔案復制到其中\copy
with json_data(json) as (
values
('{"x": 1}'::jsonb),
('{"x": 2, "y": 3}'),
('{"x": 8, "z": 3}'),
('{"x": 5, "y": 2, "z": 3}')
)
select
(json->'x')::int as x,
(json->'y')::int as y,
nullif(json- 'x'- 'y', '{}') as json
from json_data
閱讀檔案中的JSON 函式和運算子。
筆記。在 Postgres 10 或更早版本中,使用->>運算子而不是->.
要在匯入 json 資料時自動轉換,請定義觸發器:
create table json_data(json jsonb);
create or replace function json_data_trigger()
returns trigger language plpgsql as $$
begin
insert into target_table
select
(new.json->>'x')::int,
(new.json->>'y')::int,
nullif(new.json- 'x'- 'y', '{}');
return new;
end $$;
create trigger json_data_trigger
before insert on json_data
for each row execute procedure json_data_trigger();
在Db<>Fiddle中測驗它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483438.html
標籤:sql json PostgreSQL 触发器 插入
