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

标签 sql json postgresql postgresql-9.4 jsonb

我在 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}]
  • 如何找到所有行的最大 numberOfCarrot?
  • 如何找到一行的最大 numberOfCarrot?
  • 如何找到 numberOfCarrot 优于或低于某物的行?
  • 如何在 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/

相关文章:

MySQL 组合来自许多行的字符串,例如 SUM for int

c# - JsonResult 返回空 Json

database-design - 在 PostgreSQL 中实现 Type-2 缓慢变化维度

ruby:从嵌套的 json 中提取字段

mysql - 为什么我的加入不起作用?

java - 从 postgresql 填充 jTable

sql - 使用 SUM 函数在 SQL 中连接表

sql - 如何在 SOQL 中对同一对象进行内部或子查询

php - 将日期传递给 where 子句时出错

javascript - 迭代 jQuery 格式化 JSON 不正确