sql - 针对 jsonb 数组中的特定对象

标签 sql json postgresql jsonb

我需要从表中选择符合特定条件的行,这涉及到 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[]);

因此,对于给定的示例,我将仅获取值为 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)

这里是“解释”为什么值 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/

相关文章:

javascript - 无法循环遍历 ember 模板中的 json 响应

javascript - 在 AngularJS 中使用 underscore.js 合并两个数组

python - postgresql 数据库查询后 python 脚本输出中存在未知空格

3 种不同测试的首次尝试的 MYSQL 平均分数 - IN GROUP BY

sql - 使用合并语句过滤目标表的最佳方法是什么

mysql - 使用同一电子邮件批量删除用户

php - 连接postgres和php,使用d3.js可视化

sql - SQL Server 根据条件插入和更改数据

javascript - 如何序列化Json javascript

sql - 无法在 Postgresql 中加载 CSV 文件