我在 Postgresql 中有 jsonb 欄位(資料),其結構如下:
{ "id" => { "some_key" => [1, 2, 3] } }
我需要將值遷移到不同的欄位。
t.jsonb "data"
t.integer "portals", default: [], array: true
當我試圖這樣做時:
UPDATE table_name
SET portals = ARRAY[data -> '1' ->> 'portals']
WHERE id = 287766
它引發了一個錯誤:
Caused by PG::DatatypeMismatch: ERROR: column "portals" is of type integer[] but expression is of type text[]
uj5u.com熱心網友回復:
這是一種方法。但是,如果您按照您應該做的那樣搜索該站點,您會得到更多。
架構
create table t (
data jsonb
);
insert into t values ('{"1" : { "k1" : [1,2,3,5]} }');
insert into t values ('{"2" : { "k2" : [4,5,6,7]} }');
create table i (
id int,
v int[]
)
一些測驗
select data -> '1' -> 'k1'
from t
where data ? '1'
;
insert into i values(1,ARRAY[1,2,3]);
update i
set v = (select replace(replace(data -> '1' ->> 'k1', '[', '{'), ']', '}')::int[] from t where data ? '1')
where id = 1;
select * from i;
就像您所做的那樣,上面的內容將陣列作為文本。之后,只需進行一些文本替換即可將文本轉換為integer array literal.
DB小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483041.html
標籤:sql PostgreSQL
