在PostgreSQL中,如何选择具有jsonb数组的行以及范围之间的任何元素?

时间:2015-05-27 13:44:45

标签: postgresql jsonb

我有以下(简化)结构:

 id |            j            
----+-------------------------
  1 | {"price": [1, 2, 3, 4]}
  2 | {"price": [4, 5, 6, 7]}
  3 | {"something": "else"}

理想情况下,我想查询这样的内容:

select id from testjson where any(j->'price') between 5 and 8;

我设法找到了解决方法:

select id from testjson where any_between(j->'price',5,8);

之前已定义以下内容:

CREATE OR REPLACE FUNCTION jsonb_array_bigint(_j jsonb) RETURNS bigint[] AS
$$
SELECT array_agg(elem::text::bigint) FROM jsonb_array_elements(_j) AS elem
$$
LANGUAGE sql IMMUTABLE;

CREATE OR REPLACE FUNCTION any_between(_j jsonb,lower bigint, higher bigint) RETURNS boolean AS
$$
select (lower <= any(arr) and higher >= any(arr)) from jsonb_array_bigint(_j) as arr  
$$
LANGUAGE sql IMMUTABLE;

这有效,但有点黑,看起来效率不高。 还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用json_array_elements将数组扩展为行:

select  distinct id
from    Table1
cross join    
        json_array_elements((j->'price')::json)
where   value::text::int between 5 and 8

Example at SQL Fiddle.示例适用于json而不是jsonb,因为SQL Fiddle尚不支持9.4。