DDD
DDD

Reputation: 45

how to join on the values returned from Json_array_elements in postgresql?

Structure of "Order" table:

objectId text, 
subOrders jsonb

structure of Jsonb: array of jsonb objects. eg.

[
   {
      "className":"SubOrder",
      "__type":"Pointer",
      "objectId":"tIENf1PCHO"
   },
   {
      "className":"SubOrder",
      "__type":"Pointer",
      "objectId":"yKVDFEuWx7"
   }
]

Structure of "SubOrder" table:

objectId text,
orderitems jsonb

structure of suborder.orderitems jsonb, eg:

[
   {
      "className":"SubOrderItem",
      "__type":"Pointer",
      "objectId":"6d1DLrmOTD"
   },
   {
      "className":"SubOrderItem",
      "__type":"Pointer",
      "objectId":"xK6mR2PDDU"
   }
]

I need to join Order.suborders.objectId with suborder.objectid

AS Order.suborders column is a jsonb array of objects, I am taking the array elements as below.

select jsonb_array_elements("subOrders")->>'objectId' 
from "Order"

Then is the problem to join the returned objectId with the Suborder table.

Upvotes: 1

Views: 6365

Answers (2)

user330315
user330315

Reputation:

Put the function call into the FROM clause and de-reference the actual field of the JSON object later.

select o.object_id, so.*
from "Order" o
  cross join lateral jsonb_array_elements(sub_orders) j(suborder)
  join sub_order so on so.object_id = j.suborder ->> 'objectId' 

Online example: http://rextester.com/GQBF88668

Upvotes: 4

M Ashraful A
M Ashraful A

Reputation: 637

I would use WITH Queries

WITH suborders_object AS(
select jsonb_array_elements("subOrders")->>'objectId' AS obid from Order
)
SELECT * FROM suborders_object JOIN Order ON (suborders_object.obid = Order.id);

or any way you like to join suborders_object as like a table.

Upvotes: 2

Related Questions