json - 如何过滤jsonb数组元素

标签 json postgresql aggregate-functions jsonb

我有一个包含 jsonb 列的表,其中包含一个对象数组:

create table my_table(
    id int primary key, 
    phones jsonb);

对象由电话号码和状态组成。
insert into my_table values
(1, 
'[
    {
        "phone": "929908338",
        "status": "active"
    },
    {
        "phone": "927007729",
        "status": "inactive"
    },
    {
        "phone": "927220419",
        "status": "inactive"
    },
    {
        "phone": "928200028",
        "status": "inactive"
    },
    {
        "phone": "927183322",
        "status": "inactive"
    },
    {
        "phone": "928424554",
        "status": "active"
    },
    {
        "phone": "927779383",
        "status": "inactive"
    }
]');

我想在一行中获得所有处于事件状态的手机。预期输出:
["929908338","928424554"]

最佳答案

使用 jsonb_array_elements()取消嵌套 jsonb 数组:

select id, elem
from my_table
cross join jsonb_array_elements(phones) as elem

 id |                     elem                     
----+----------------------------------------------
  1 | {"phone": "929908338", "status": "active"}
  1 | {"phone": "927007729", "status": "inactive"}
  1 | {"phone": "927220419", "status": "inactive"}
  1 | {"phone": "928200028", "status": "inactive"}
  1 | {"phone": "927183322", "status": "inactive"}
  1 | {"phone": "928424554", "status": "active"}
  1 | {"phone": "927779383", "status": "inactive"}
(7 rows)

添加条件以获取您要查找的元素:
select id, elem
from my_table
cross join jsonb_array_elements(phones) as elem
where elem->>'status' = 'active'

 id |                    elem                    
----+--------------------------------------------
  1 | {"phone": "929908338", "status": "active"}
  1 | {"phone": "928424554", "status": "active"}
(2 rows)

使用聚合函数 jsonb_agg()在单行中获取结果:
select id, jsonb_agg(elem->'phone') as active_phones
from my_table
cross join jsonb_array_elements(phones) as elem
where elem->>'status' = 'active'
group by id

 id |       active_phones        
----+----------------------------
  1 | ["929908338", "928424554"]
(1 row) 

关于json - 如何过滤jsonb数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54006818/

相关文章:

php - Json_encode-将数组转换为json对象

javascript - 将 json 键映射到 javascript 对象

python - psycopg2如何处理TypeError : not all arguments converted during string formatting

sql - PostgreSQL 中的 date_trunc 5 分钟间隔

mysql - #1055 - SELECT 列表的表达式 #2 不在 GROUP BY 子句中并且包含非聚合列 'osunemonitor.r.entry_date'

jquery datatables - 从 json 获取列

arrays - jq & bash : make JSON array from variable

postgresql - Hibernate 与分区表

ruby-on-rails - Rails 嵌套属性正确地将 parent_id 分配为索引,但未分配其他属性

python - 在某些条件下从数据框中删除重复项