You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL如何提取jsonb列部分字段按新分组封装后生成新表

你可以直接用PostgreSQL的jsonb_build_object函数构造你需要的JSON结构,通过CREATE TABLE ... AS SELECT语法直接生成新表:

CREATE TABLE points_red AS
SELECT
  node_id,
  jsonb_build_object(
    'addInfo',
    jsonb_build_object(
      'name', tags -> 'name',
      'brand', tags -> 'brand',
      'amenity', tags -> 'amenity'
    )
  ) AS tags,
  geom
FROM points;

如果需要自动剔除原tags中不存在、值为null的字段,可以搭配jsonb_strip_nulls函数使用:

CREATE TABLE points_red AS
SELECT
  node_id,
  jsonb_build_object(
    'addInfo',
    jsonb_strip_nulls(
      jsonb_build_object(
        'name', tags -> 'name',
        'brand', tags -> 'brand',
        'amenity', tags -> 'amenity'
      )
    )
  ) AS tags,
  geom
FROM points;

执行上述语句后会直接生成结构和数据都符合要求的points_red表,新表的tags字段类型也会自动继承为jsonb类型。

内容的提问来源于stack exchange,提问作者Tibor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:54:03