Postgres select 其中 json 数组包含 json

Postgres select where in json array containing json

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

[{"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}]

您需要一个唯一的列(通常是主键,比方说 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)