简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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