我正在尝试运行 Postgres SQL 调用以将数据从
jsonb
字段迁移到每个属性的单独字段,但由于某种原因,该过程不适用于嵌套字段。
{
"basis": "relative",
"defined": "2023-06-21T10:21:16.979",
"absolute": "2023-06-30T00:00:00.000",
"relative": {
"value": 0,
"period": "month"
}
}
正在运行的 SQL 是:
update gd_task_instance
set
scheduled_basis = CAST(scheduled->>'basis' AS TEXT),
scheduled_defined = CAST(scheduled->>'defined' as TIMESTAMP),
scheduled_absolute = CAST(scheduled->>'absolute' AS DATE),
scheduled_relative_value = CAST(scheduled->'relative->value' AS INT),
scheduled_relative_period = CAST(scheduled->'relative->>period' AS TEXT);
最后两个字段“scheduled_relative_value”和“scheduled_relative_period”未设置。
有什么建议吗?
找到答案...
update gd_task_instance
set
scheduled_basis = CAST(scheduled->>'basis' AS TEXT),
scheduled_defined = CAST(scheduled->>'defined' as TIMESTAMP),
scheduled_absolute = CAST(scheduled->>'absolute' AS DATE),
scheduled_relative_value = CAST(scheduled['relative']['value'] AS INT),
scheduled_relative_period = CAST(scheduled['relative']['period'] AS TEXT);
将
'relative->value'
替换为
'relative' ->> 'value'
同样适用于
period
。
UPDATE gd_task_instance
SET scheduled_basis = t.scheduled ->> 'basis'
, scheduled_defined = (t.scheduled ->> 'defined')::timestamp
, scheduled_absolute = (t.scheduled ->> 'absolute')::date
, scheduled_relative_value = (t.scheduled #>> '{relative,value}')::int
, scheduled_relative_period = t.scheduled #>> '{relative,period}'
FROM (
SELECT json
'{
"basis": "relative",
"defined": "2023-06-21T10:21:16.979",
"absolute": "2023-06-30T00:00:00.000",
"relative": {
"value": 0,
"period": "month"
}
}'
) t(scheduled)
WHERE id = 1
RETURNING *
;
对于两个或更多嵌套级别,您可以缩短语法:
t.scheduled -> 'relative' ->> 'period'
#>>
运算符:
t.scheduled #>> '{relative,period}'
转换为
text
是多余的,这已经是结果类型了。