简体   繁体   English

从postgres jsonb列中提取字段

[英]Extract fields from postgres jsonb column

I have a postgres table with jsonb column, which has the value as follows: 我有一个带有jsonb列的postgres表,其值如下:

 id  |  messageStatus       |   payload
-----|----------------------|-------------
1    |    123               | {"commissionEvents":[{"id":1,"name1":"12","name2":15,"name4":"apple","name5":"fruit"},{"id":2,"name1":"22","name2":15,"name4":"sf","name5":"fdfjkd"}]}
2    |    124               | {"commissionEvents":[{"id":3,"name1":"32","name2":15,"name4":"sf","name5":"fdfjkd"},{"id":4,"name1":"42","name2":15,"name4":"apple","name5":"fruit"}]}
3    |    125               | {"commissionEvents":[{"id":5,"name1":"42","name2":15,"name4":"apple","name5":"fdfjkd"},{"id":6,"name1":"52","name2":15,"name4":"sf","name5":"fdfjkd"},{"id":7,"name1":"62","name2":15,"name4":"apple","name5":"fdfjkd"}]}

here payload column is a jsonb datatype, I want to write a postgres query to fetch name1 from commissionEvents where name4 = apple. 这里有效负载列是一个jsonb数据类型,我想编写一个postgres查询来从CommissionEvents中获取name1,其中name4 = apple。

So my result will be like: 所以我的结果将是:

在此处输入图片说明

Since I was new to this jsonb, can anyone please suggest me some solution for it. 由于我是这个jsonb的新手,所以有人可以建议我一些解决方案。

You need to unnest all array elements, then you can apply a WHERE condition on that to filter out those with the desired name. 您需要取消嵌套所有数组元素,然后可以对其应用WHERE条件,以过滤出具有所需名称的元素。

select t.id, x.o ->> 'name1'
from the_table t
  cross join lateral jsonb_array_elements(t.payload -> 'commissionEvents') as x(o)
where x.o ->> 'name4' = 'apple'

Online example: https://rextester.com/XWHG26387 在线示例: https : //rextester.com/XWHG26387

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM