简体   繁体   English

在 PostgreSQL 中是否有一种自动方法将 JSON(B) 列拆分为多个列?

[英]Is there an automated way to split a JSON(B) column into multiple columns in PostgreSQL?

So I have a PostgreSQL (TimescaleDB) table that looks like this:所以我有一个 PostgreSQL (TimescaleDB) 表,看起来像这样:

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

And I would like to split the JSON(B) column into multiple columns like this:我想将 JSON(B) 列拆分为多个列,如下所示:

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

I looked into the JSON Processing Functions and it seems that those require finding all the JSON(B) attributes and types.我查看了JSON 处理函数,似乎这些函数需要找到所有 JSON(B) 属性和类型。 Is there a way to do this automatically?有没有办法自动执行此操作?

There is no way to make this dynamic.没有办法让这个动态。 The number (and types) of all columns of a query must be known to the database when parsing the statement, long before it's actually executed.解析语句时,数据库必须知道查询的所有列的数量(和类型),早在实际执行之前很久。


If you always have the same structure you can create a type:如果您始终具有相同的结构,则可以创建一个类型:

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

and then use jsonb_populate_record()然后使用jsonb_populate_record()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM