2015-06-01 52 views
0

我有表格。Postgresql加入jsonb

Orders表:

id: integer 
items: jsonb 

項目表:

id: integer 
title: string 
price: integer 

例如爲了記錄

id: 1, 
items: { 
    "1"=>{"qty"=>3}, 
    "3"=>{"qty"=>12} 
    } 

例如項目記錄

id:1, title: "Tesla model S" 
id:2, title: "Tesla model W" 
id:3, title: "Tesla model D" 

請幫助得到的結果:

id:1, title: "Tesla model S", qty: 3 
id:3, title: "Tesla model D", qty: 12 

回答

0

最終,我做到了。 該查詢起作用。

 SELECT 
     json_data.key AS id, 
     json_data.value::jsonb->'qty' AS qty, 
     items.title as title 
     FROM orders, jsonb_each_text(orders.items) AS json_data 
     INNER JOIN items ON items.id = json_data.key::int 
     WHERE orders.id=1