【问题标题】:Get an array element from an array in a json attribute of a jsonb column从 jsonb 列的 json 属性中的数组中获取数组元素
【发布时间】:2021-03-09 11:59:23
【问题描述】:

我正在使用 postgres 数据库,并且我在 jsonb 列的 json 属性中有一个数组,我需要获取该数组的第一个元素。 jsonb_column 结构如下:

"IndustryCode": {
"Code": "111110",
"Keys": [
  "11",
  "111",
  "111110"
],}

到目前为止,我可以通过发出下面的查询来获取所有查询元素

select jsonb_array_elements(jsonb_column->'IndustryCode'->'Keys' ) from myindustry;

如何查询以获取第一个元素?

【问题讨论】:

    标签: arrays json postgresql jsonb


    【解决方案1】:

    如果您只想要第一个元素,则无需取消嵌套整个数组。 -> operator 也接受指定数组索引的整数。

    select jsonb_column -> 'IndustryCode' -> 'Keys' ->> 0 
    from myindustry;
    

    注意我使用->> 将值返回为text 而不是jsonb

    【讨论】:

    • 非常感谢您的帮助@a_horse_with_no_name
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2018-03-16
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多