1

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.

1
  • @ a_horse_with_no_name thanks for editing the question. Please help. Commented Apr 11, 2018 at 8:32

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

6 Comments

my query is like thisselect o.*, j.*, ot.* from "Order" o cross join lateral select jsonb_array_elements("subOrders")->>'objectId' as j(object_id) from "Order" join "SubOrder" ot on ot."objectId" = j.object_id; and my error is syntax error at or near "->>" LINE 3: ...oss join lateral jsonb_array_elements("subOrders")->>'object... Please help
all my objectid are text fields only.
select o.*, j.*, ot.* from "Order" o cross join lateral jsonb_array_elements(o."subOrders")->>'objectId' as j("object_id") join "SubOrder" ot on ot."objectId" = j."object_id";... sorry that one is not correct. even with this there is same error.'
Edited my question with the structure of the tables involved and the requirement. Thanks.
Done. Thank a lot.
|
2

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.

2 Comments

Thanks much Ashraful. can you also share the other method like joining with other table pls?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.