【问题标题】:Get all the values from nested JSON arrays in PostgreSQL从 PostgreSQL 中的嵌套 JSON 数组中获取所有值
【发布时间】:2020-07-10 01:14:48
【问题描述】:

我想使用原始查询提取abc 数组中的所有app_indexe。我正在使用 PostgreSQL 10.9 的数据库。我成功地提取到abc 键。我能得到的是通过传递数组的索引号。但我想要所有的 app_index。

无索引:

select v_info->'abc' from table1

带索引: select v_info->'abc'->>0 from table1

{
        "id": 1406711300166,
        "abc": [ 
            {
                "am": "1.74",
                "am_set": {
                    "sh_mon": {
                        "am": "1.74",
                        "cur_code": "ABC"
                    },
                    "pre_money": {
                        "amount": "1.74",
                        "code": "ABC"
                    }
                },
                "app_index": 0
            },
           {
                "am": "1.74",
                "am_set": {
                    "sh_mon": {
                        "am": "1.74",
                        "cur_code": "ABC"
                    },
                    "pre_money": {
                        "amount": "1.74",
                        "code": "ABC"
                    }
                },
                "app_index": 1
            }
        ],
        "xyx": 0,
        "zyx": "random var"
    }

我需要的是abcapp_index 中的所有值。

输出

abc_index
----------
0
1

【问题讨论】:

  • 请以表格文本形式向我们展示您期望的结果。
  • @GMB 我已经编辑了我的问题。你可以得到一个粗略的想法。
  • 你使用的是什么版本的 postgres
  • @HaleemurAli PostgreSQL 10.9

标签: sql arrays json postgresql unnest


【解决方案1】:

您可以使用json(b)_array_elements() 取消嵌套数组,然后访问属性app_index 的值:

select el -> 'app_index' abc_index
from mytable t
cross join lateral jsonb_array_elements(t.v_info -> 'abc') a(el)

Demo on DB Fiddle

| abc_index | | :-------- | | 0 | | 1 |

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2016-06-06
    • 2020-12-10
    • 2019-02-21
    • 1970-01-01
    相关资源
    最近更新 更多