【问题标题】:Getting values from array of objects jsonb postgresql从对象数组jsonb postgresql中获取值
【发布时间】:2018-07-02 14:32:35
【问题描述】:

我将一些 id 和名称存储在一个像这样的对象的 jsonb 数组中

[{"id":"1","name":"abc"},{"id":"2","name":"cde"}]

我的桌子是这样的

id      userinfo
1       [{"id":"1","name":"abc"},{"id":"2","name":"cde"}]
2       [{"id":"3","name":"fgh"},{"id":"4","name":"ijk"}]    

我正在尝试选择 id 为 1 的所有记录,但我只想获取 userinfo 对象中的 id 我不想要名称

我试过了

select distinct userinfo->'name' from table where id = 1

但这给了我空值

这将适用于该查询

select distinct userinfo->0->'name' from table where id = 1

但我不知道索引,所以如何使用此查询来获得我想要的结果

谢谢

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您需要通过取消嵌套数组来规范化数据,然后您可以访问每个元素。

    select ui.info ->> 'id' as id,
           ui.info ->> 'name' as name
    from the_table t
      cross join lateral jsonb_array_elements(t.userinfo) as ui(info)
     where t.id = 1;
    

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

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 2022-07-02
      • 2019-09-26
      • 2017-10-25
      • 1970-01-01
      • 2017-06-23
      相关资源
      最近更新 更多