从嵌套 jsonb 属性更新单独的表列

问题描述 投票:0回答:2

我正在尝试运行 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”未设置。

有什么建议吗?

sql postgresql jsonb supabase-database
2个回答
0
投票

找到答案...

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);

0
投票

'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
是多余的,这已经是结果类型了。

© www.soinside.com 2019 - 2024. All rights reserved.