Postgres选择包含json的json数组中的位置

时间:2017-05-24 15:37:07

标签: sql json postgresql postgresql-9.4 jsonb

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

[{"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}]
  • 如何找到所有行的max numberOfCarrot?
  • 如何找到一行的max numberOfCarrot?
  • 如何找到numberOfCarrot优于或低于某些内容的行?
  • 如何在json数组中找到numberOfCarrot优于或低于某些东西的元素?

1 个答案:

答案 0 :(得分:3)

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