2017-01-09 83 views
1

我正在使用內部連接來連接3個表,所有者,存儲和計算機。 我試圖從多個表中查看輸出JSON是這樣的:格式JSON Postgresql

SELECT ow.*, st.*, ma.* 
FROM owner ow 
    INNER JOIN st.store ON ow.OwnerId = st.OwnerId 
    INNER JOIN machine ma ON ma.StoreId = st.StoreId; 

我想JSON格式是這樣的:

{ 
    "OwnerId": "1d2dd", 
    "Name": "name test", 
    "Store":[{ 
     "StoreId": "s3ss5", 
     "Name": "Store1", 
     "Code": "bla", 
     "Machine":[{ 
      "MachineId": "axpeo", 
      "Name": "Machine1", 
      "Type": "type1" 
      }] 
     }, 
     { 
     "StoreId": "ddf22", 
     "Name": "Store2", 
     "Code": "ble", 
     "Machine":[{ 
      "MachineId": "weds", 
      "Name": "Machine2", 
      "Type": "type2" 
      }, 
      { 
      "MachineId": "axdso", 
      "Name": "Machine3", 
      "Type": "type3" 
      }] 
     }] 
} 

但JSON沒有格式化,這樣 返回我使用PostgreSQL的。

+0

? –

+1

普通的SQL select語句永遠不會返回JSON,請查看Postgres中可用的JSON函數:https://www.postgresql.org/docs/current/static/functions-json.html –

回答

0

要做到這一點,最簡單的(也許唯一明智的)方法是在表級別構建從個人記錄JSON子文檔,然後才分層加入他們:

SELECT json_build_object('OwnerId', ownerid, 
         'Name', name, 
         'Store', stores) 
FROM owner 
JOIN (
    SELECT ownerid, 
      json_agg(
       json_build_object('StoreId', storeid, 
           'Name', name, 
           'Code', code, 
           'Machine', machines)) AS stores 
    FROM store 
    JOIN (
     SELECT storeid, 
       json_agg(
        json_build_object('MachineId', machineid, 
            'Name', name, 
            'Type', type)) AS machines 
     FROM machine 
     GROUP BY storeid) m USING (storeid) 
    GROUP BY ownerid) s USING (ownerid); 
0

輸出是不正是我想要的,但它是更好的... ...這是輸出

[{ 
    "OwnerId": "1d2dd", 
    "Name": "name test", 
    "Store":{ 
     "StoreId": "s3ss5", 
     "Name": "Store1", 
     "Code": "bla", 
     "Machine":{ 
      "MachineId": "axpeo", 
      "Name": "Machine1", 
      "Type": "type1" 
      } 
     } 
}, 
{ 
    "OwnerId": "1d2dd", 
    "Name": "name test", 
    "Store":{ 
     "StoreId": "ddf22", 
     "Name": "Store2", 
     "Code": "ble", 
     "Machine":{ 
      "MachineId": "weds", 
      "Name": "Machine2", 
      "Type": "type2" 
      } 
     } 

}, 
{ 
    "OwnerId": "1d2dd", 
    "Name": "name test", 
    "Store":{ 
     "StoreId": "ddf22", 
     "Name": "Store2", 
     "Code": "ble", 
     "Machine":{ 
      "MachineId": "axdso", 
      "Name": "Machine3", 
      "Type": "type3" 
      } 
     } 
}] 

它不會從同店加盟機器但像什麼語言數組