如何从 Postgresql jsonb 列中查询值

How to query value from Postgresql jsonb colum

在 Postgres 数据库中,我有一个 jsonb 列,其中包含如下项的维度:

{
 "370730255061723346": {"volume": 3, "weight": 3200, "length": 8}, 
 "370730255061723353": {"volume": 2, "weight": 3600, "length": 9}
}

由于第一个键是一个 ID,我正在努力解决 jsonb 条目中其他信息的寻址问题:

您可以使用 json 函数,例如 jsonb_each、jsonb_to_record、路径提取运算符...即:

drop table if exists sample;

create temporary table sample
(
    id serial,
    dummy jsonb
);

insert into sample (dummy)
values ('{
  "370730255061723346": {
    "volume": 3,
    "weight": 3200,
    "length": 8
  },
  "370730255061723353": {
    "volume": 2,
    "weight": 3600,
    "length": 9
  }
}');

select *
from sample;

with myData as (
    select id, d.length, d.volume, d.weight
    from sample,
         lateral (select * from jsonb_each(sample.dummy)) t,
         lateral (select * from jsonb_to_record(t.value) as r(length int, volume int, weight int)) d
)
select sum(length)
from myData
where id = 1;

您需要将 JSON 转换为一系列行,然后再聚合回来。为了避免对整个查询进行分组,我会在派生的 table:

中进行聚合
select t.other_column, d.*
from the_table t
   cross join lateral (
      select count(*) as num_elements, 
             sum((value ->> 'length')::int) as total_length
      from jsonb_each(t.the_column) as e(id, value)
   ) as d