我需要从表中选择符合特定条件的行,这涉及到 jsonb 对象字段比较。
在下面的示例中,我只想获取值在数组中的对象指定的最小/最大范围内的行:对于任何给定的行,如果它的 array_of_objects
“包含”(使用最小/最大比较)一个值
,我需要那一行。
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[]);
因此,对于给定的示例,我将仅获取值为 8
和 22
的行。
最佳答案
如果你想要原始列:
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)
这里是“解释”为什么值 22 没有进入它(array_of_objects[1]->>max 小于 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
关于sql - 针对 jsonb 数组中的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42107392/