针对 jsonb 数组中的特定对象

Targeting specific objects in jsonb array

我需要来自 table 的 select 行匹配涉及 jsonb 对象字段比较的特定条件。

在下面的示例中,我只想获取值在数组中的对象指定的 min/max 范围内的行:对于任何给定的行,如果其 [= 中的任何对象11=] "contains"(使用min/max比较)一个value,我需要那一行。

CREATE TABLE test_table (
  id serial,
  value int,
  array_of_objects jsonb[]
);

INSERT INTO
  test_table (value, array_of_objects)
VALUES
  (8, ARRAY ['{"min":5,"max":15}', '{"min":4,"max":18}']::jsonb[]),
  (6, ARRAY ['{"min":12,"max":18}', '{"min":19,"max":22}']::jsonb[]),
  (22, ARRAY ['{"min":16,"max":18}', '{"min":34,"max":47}']::jsonb[]);

因此,对于给定的示例,我只会获得值 822.

的行

如果您想要原始专栏:

t=# with a as (select unnest(array_of_objects) j,* from test_table)
select distinct id,value, array_of_objects
from a
where (j->>'min')::int < value and (j->>'max')::int > value;
 id | value |                     array_of_objects
----+-------+-----------------------------------------------------------
  1 |     8 | {"{\"max\": 15, \"min\": 5}","{\"max\": 18, \"min\": 4}"}
(1 row)

这里是 "explanation" 为什么值 22 没有进入它(array_of_objects[1]->>最大值小于 22:

Time: 0.441 ms
t=# with a as (select unnest(array_of_objects) j,* from test_table)
select distinct id,value,j
from a
where (j->>'min')::int < value and (j->>'max')::int > value;
 id | value |           j
----+-------+-----------------------
  1 |     8 | {"max": 18, "min": 4}
  1 |     8 | {"max": 15, "min": 5}
(2 rows)

Time: 0.390 ms

在 PostgreSQL 10 之后的某个时间可以避免使用 unnest

有一个PR in PostgreSQL Commitfest implementing a huge chunk of JSON-related functions, standardised as part of the latest SQL 2016标准:

这是一个例子:

CREATE TABLE my_table (
  title VARCHAR,
  number INTEGER,
  my_array JSONB
);

INSERT INTO my_table (title, number, my_array) VALUES
  ('not expected', 6, '[{"min": 1, "max": 5}, {"min": 7, "max": 10}]'::JSONB),
  ('expected', 7, '[{"min": 1, "max": 5}, {"min": 7, "max": 10}]'::JSONB);

SELECT *
  FROM my_table
 WHERE JSON_EXISTS(my_array, '$[*] ? (@.min < $x && $x <= @.max)' PASSING number AS x);