将PSQL表迁移到没有空值的jsonb

时间:2017-10-02 09:55:47

标签: postgresql jsonb

我必须将包含键和多个值的表(可空)迁移到jsonb表示的键值postgres表中。

K | V1 | V2 | V3  | V4
-----------------------
1 | a  | 42 |     | cde

我可能需要中间表才能做到(没有它可以做到吗?)。但第一个挑战是正确获取价值。 我注意到json_agg会给我一些类似

的内容

{"K":1, "V1":"a", "V2":42, "V3":null, "V4":"cde"}

相反,我希望得到像

这样的东西

{"V1":"a", "V2":42, "V4":"cde"}

如何过滤掉jsonb中的字段?

有没有办法在没有中间表的情况下完成迁移?

所以我想要的最后一件事看起来像这样:

K | V
------------------------------------
1 | {"V1":"a", "V2":42, "V4":"cde"}

2 个答案:

答案 0 :(得分:2)

使用函数jsonb_strip_nulls(to_jsonb(t)),示例:

with my_table(K, V1, V2, V3, V4) as (
values
    (1, 'a', 42, null, 'cde')
)

select k, jsonb_strip_nulls(to_jsonb(t))- 'k' as jsonb_data
from my_table t;

 k |             jsonb_data             
---+------------------------------------
 1 | {"v1": "a", "v2": 42, "v4": "cde"}
(1 row)

答案 1 :(得分:1)

只需将行转换为jsonb并删除k键:

select k,jsonb_object_agg(key, val)
from (
  select k, 'v1' as key, v1 as val
  from t
  where v1 is not null
  union all
  select k, 'v2', v2::text
  from t
  where v2 is not null
  union all
  select k, 'v3', v3::text
  from t
  where v3 is not null
  union all
  select k, 'v4', v4
  from t
  where v4 is not null
) t
group by k