从postgres jsonb列中提取字段

时间:2019-07-11 09:12:41

标签: sql postgresql jsonb

我有一个带有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"}]}

这里有效负载列是jsonb数据类型,我想编写一个postgres查询,以从name4 = apple的CommissionEvents中获取name1。

所以我的结果将是:

enter image description here

由于我是这个jsonb的新手,所以有人可以为我提供一些解决方案吗?

1 个答案:

答案 0 :(得分:2)

您需要取消嵌套所有数组元素,然后可以对此应用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'

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