我在postgresql 9.4数据库中有一个带有jsonb字段的表。
一些示例行:

[{"name": "145119603", "numberOfCarrot": 2}]
[{"name": "1884595530", "numberOfCarrot": 1}]
[{"name": "363058213", "numberOfCarrot": 1}]
[{"name": "1427965764", "numberOfCarrot": 1}]
[{"name": "193623800", "numberOfCarrot": 43}, {"name": "419955814", "numberOfCarrot": 0}]
[{"name": "624635532", "numberOfCarrot": 0}, {"name": "1884595530", "numberOfCarrot": 1}]
[{"name": "791712670", "numberOfCarrot": 1}]
[{"name": "895207852", "numberOfCarrot": 0}]
[{"name": "144695994", "numberOfCarrot": 3}, {"name": "384217055", "numberOfCarrot": 23}]
[{"name": "1079725696", "numberOfCarrot": 10}]

我怎样才能找到所有排胡萝卜的最大数量?
我怎样才能找到一排胡萝卜的最大数量?
我怎样才能找到胡萝卜的数量比什么东西高或低的那一排呢?
如何在json数组中找到numberOfCarrot优于或低于某个值的元素?

最佳答案

您需要一个唯一的列(通常是主键,例如id),因此您的数据应该如下所示:

(1, '[{"name": "145119603", "numberOfCarrot": 2}]'),
(2, '[{"name": "1884595530", "numberOfCarrot": 1}]'),
...

在横向连接中使用jsonb_array_elements()。示例:
select max(value->>'numberOfCarrot')::int
from my_table,
jsonb_array_elements(jdata);

 max
-----
  43
(1 row)

select id, max((value->>'numberOfCarrot')::int)
from my_table,
jsonb_array_elements(jdata)
group by 1
order by 1;

 id | max
----+-----
  1 |   2
  2 |   1
  3 |   1
  4 |   1
  5 |  43
  6 |   1
  7 |   1
  8 |   0
  9 |  23
 10 |  10
(10 rows)

如何使用where
select id, value->>'numberOfCarrot' as "numberOfCarrot"
from my_table,
jsonb_array_elements(jdata)
where (value->>'numberOfCarrot')::int > 20;

 id | numberOfCarrot
----+----------------
  5 | 43
  9 | 23
(2 rows)

select id, array_agg(value->>'numberOfCarrot') as "numberOfCarrot"
from my_table,
jsonb_array_elements(jdata)
where (value->>'numberOfCarrot')::int > 2
group by 1
order by 1;

 id | numberOfCarrot
----+----------------
  5 | {43}
  9 | {3,23}
 10 | {10}
(3 rows)

关于sql - Postgres选择包含JSON的JSON数组中的位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44162909/

10-10 02:24