【发布时间】: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