【问题标题】:get a single element from a JSON array in postgreSQL从 postgreSQL 中的 JSON 数组中获取单个元素
【发布时间】:2016-08-20 11:19:33
【问题描述】:

我需要根据我定义的一些规则从存储在 postgreSQL DB 中的数组中检索单个元素,然后将其与其他一些数据连接起来。让我举个例子:

postgres=# SELECT * FROM list;
id    | list
------+-----------------------------------------------------------------------------
0ab2c | [{type: 1, val: a}, {type: 3, val: c}, {type: 4, val: d}]
01abc | [{type: 1, val: a}, {type: 2, val: b}]
a0b31 | [{type: 1, val: a}, {type: 2, val: b}, {type: 3, val: c}]

postgres=# SELECT * FROM elems
eid | listId
----+-------
10  | 0ab2c
11  | 01abc
12  | a0b31

我想list 表中提取一个元素,并将结果与​​elem 表连接起来,以获得类似:

eid | listId | type | val
----+--------+------+-----
10  | 0ab2c  |   3  |  c
11  | 01abc  |   2  |  b
12  | a0b31  |   2  |  b

特别是json数组中的元素要根据一个函数来选择(我用JS写的,因为我比较熟悉,但是函数当然需要在plpgSQL中):

function getElemFromList(list){
    var allowedTypes = [2, 3];
    var result;
    for(var i = 0; i < list.length; i++){
        if(list[i].indexOf(allowedTypes) !== -1){
            return list[i];
        }
    }
}

列表中的元素属于某种类型并且是数组中第一个允许的元素。

【问题讨论】:

    标签: sql arrays json postgresql stored-functions


    【解决方案1】:

    这应该很简单。看起来您需要此页面中的运算符:

    http://www.postgresql.org/docs/current/static/functions-json.html

    如果您希望循环遍历 pl/pgsql 中的任何结果集,请查看以下内容:

    DO $$
    cur RECORD;
    BEGIN
    FOR cur IN SELECT * FROM LIST
    //do something with your JSON
    END LOOP;
    END $$;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2014-10-14
      相关资源
      最近更新 更多