有没有一种自动的方法可以在PostgreSQL中将JSONB列拆分为多个列?

问题描述

所以我有一个看起来像这样的Postgresql(TimescaleDB)表:

╔════════════════════════════╦═══════╦═══════╗
║            tags            ║ time  ║ value ║
╠════════════════════════════╬═══════╬═══════╣
║ {"a": "test","c": "test"} ║ 10:24 ║   123 ║
║ {"b": "test","c": "test"} ║ 10:25 ║   110 ║
║ {"b": "test"}              ║ 10:26 ║   130 ║
╚════════════════════════════╩═══════╩═══════╝

我想像这样将JSON(B)列拆分为多个列:

╔════════╦════════╦════════╦═══════╦═══════╗
║   a    ║   b    ║   c    ║ time  ║ value ║
╠════════╬════════╬════════╬═══════╬═══════╣
║ "test" ║        ║ "test" ║ 10:24 ║   123 ║
║        ║ "test" ║ "test" ║ 10:25 ║   110 ║
║        ║ "test" ║        ║ 10:26 ║   130 ║
╚════════╩════════╩════════╩═══════╩═══════╝

我查看了JSON Processing Functions,看来这些要求查找所有JSON(B)属性和类型。有没有办法自动执行此操作?

解决方法

没有办法使它动态化。解析该语句时,查询的所有列的数量(和类型)必须是数据库知道的,并且要早于实际执行。


如果您始终具有相同的结构,则可以创建一个类型:

create type tag_type as (a text,b text,c text);

然后使用jsonb_populate_record()

select (jsonb_populate_record(null::tag_type,tags)).*,time,value
from the_table;