代码之家  ›  专栏  ›  技术社区  ›  user2490003

在postgres jsonb字段中仅选择非空键

  •  2
  • user2490003  · 技术社区  · 6 年前

    我有一个带有jsonb列的postgres 9.6表

    > SELECT id, data FROM my_table ORDER BY id LIMIT 4;
    
     id |               data    
    ----+---------------------------------------
      1 | {"a": [1, 7], "b": null, "c": [8]}
      2 | {"a": [2, 9], "b": [1], "c": null}
      3 | {"a": [8, 9], "b": null, "c": [3, 4]}
      4 | {}
    

    如您所见,一些json键具有 null 价值观。

    我想排除这些-有没有简单的方法 SELECT 只有非- 无效的 要生成的键值对:

     id |               data    
    ----+---------------------------------------
      1 | {"a": [1, 7], "c": [8]}
      2 | {"a": [2, 9], "b": [1]}
      3 | {"a": [8, 9], "c": [3, 4]}
      4 | {}
    

    谢谢!

    1 回复  |  直到 6 年前
        1
  •  2
  •   a_horse_with_no_name    6 年前

    你可以使用 jsonb_strip_nulls()

    select id, jsonb_strip_nulls(data) as data
    from my_table;
    

    在线示例: http://rextester.com/GGJRW83576

    请注意,此函数不会删除 null 数组中的值。