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.

DDD
  • 45
  • 1
  • 6

2 Answers2

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

  • 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 – DDD Apr 11 '18 at 07:27
  • all my objectid are text fields only. – DDD Apr 11 '18 at 07:28
  • 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.' – DDD Apr 11 '18 at 07:43
  • Edited my question with the structure of the tables involved and the requirement. Thanks. – DDD Apr 11 '18 at 08:22
  • Done. Thank a lot. – DDD Apr 12 '18 at 06:31
  • Is the `lateral` required? – AndreKR Jul 14 '23 at 19:16
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.

M Ashraful A
  • 627
  • 6
  • 13
  • Thanks much Ashraful. can you also share the other method like joining with other table pls? – DDD Apr 11 '18 at 06:02
  • What about **[PostgreSql : Json Array to Rows using Lateral Join](https://stackoverflow.com/questions/61709474/postgresql-json-array-to-rows-using-lateral-join)**? –  May 10 '20 at 09:14