PostgreSQL - 如何获取列列表中的元素数

mon*_*top 11 postgresql json arraylist multiple-columns

这就是我的订单表的样子:

-----------------------------------------------------------
| id  | order
-----------------------------------------------------------
|1    |[{"order_quantity" : 2, "active" : TRUE, "price" : $100 }, {"order_quantity" : 4, "active" : FALSE, "price" : $200 }]
|2    |[{"order_quantity" : 2, "active" : TRUE, "price" : $170 }]
|3    |[{"order_quantity" : 2, "active" : TRUE, "price" : $120 }]
|4    |[{"order_quantity" : 2, "active" : TRUE, "price" : $150 }, {"order_quantity" : 3, "active" : TRUE, "price" : $200 }, {"order_quantity" : 5, "active" : TRUE, "price" : $200 }]
-----------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

在对每个元素中JSON括号内的元素进行计数时需要的结果WHERE active == TRUE:

------------
id  | counts
------------
|1  |   1
|2  |   1
|3  |   1
|4  |   3
------------
Run Code Online (Sandbox Code Playgroud)

这就是我正在使用但它没有提供我正在寻找的数据,因为它不会查看每个字典,看看是否 active == TRUE

SELECT id, json_array_length(order::JSON)
FROM orders

------------
id  | counts
------------
|1  |   2
|2  |   1
|3  |   1
|4  |   3
------------
Run Code Online (Sandbox Code Playgroud)

kli*_*lin 7

使用json_array_elements()选择json数组的所有元素,过滤元素并最终计算分组的剩余元素id.

select id, count(id)
from orders, json_array_elements(orders) elem
where (elem->>'active')::boolean
group by 1
order by 1;

 id | count 
----+-------
  1 |     1
  2 |     1
  3 |     1
  4 |     3
(4 rows)    
Run Code Online (Sandbox Code Playgroud)

笔记:

  • json_array_elements()FROM子句中使用set returns函数(如)作为横向连接 ;
  • json布尔值应该看起来像true(不TRUE);
  • money在json中没有类型,使用300而不是$300;
  • 使用jsonlint验证json值.