2017-04-18 238 views
0

我需要建立JSON對象在這樣的結構:PostgreSQL和嵌套JSON對象

{ 
    "id":1, 
    "name": "Jessica", //other top-level key-values 
    "add_info": { 
     "first_object":{"date":"2017-04-17","id":1}, 
     "second_object":{"date":"2017-04-17","id":1} //etc. 
    } 
} 

不幸的是我糊塗了上一個偉大但並非所示例PostgreSQL的JSON-函數大額和想不通如何實現這個更好的方式。 我嘗試這樣做:

SELECT row_to_json(t, TRUE) 
FROM (
     SELECT 
     id, name 
     , (
      (
       SELECT row_to_json(b) AS first_object 
       FROM (
         SELECT * 
         FROM table1 
         WHERE client_id = 1 
        ) b 
      ), 
      (
       SELECT row_to_json(b) AS second_object 
       FROM (
         SELECT * 
         FROM table2 
         WHERE client_id = 1 
        ) b 
      ) 
      ) AS add_info 

     FROM main_table 
     WHERE id = 1 
    ) t; 

但我發現了這一點:

{ 
    "id":1, 
    "name": "Jessica", //other top-level key-values 
    "add_info": { 
     "f1":{"date":"2017-04-17","id":1}, 
     "f2":{"date":"2017-04-17","id":1} //etc. 
    } 
} 

F1,F2! Whaat ??!

好像我可以做一些事情,給他們的名字:

SELECT row_to_json(t, TRUE) 
FROM (
     SELECT 
     id, name 
     , (
      (SELECT row_to_json(first_row) first_row 
       FROM 
       (
        SELECT row_to_json(b) AS first_object 
        FROM (
         SELECT * 
         FROM first_table 
         WHERE client_id = 1 
         ) b 
       ) AS first_row 
      ), 
      (SELECT row_to_json(second_row) second_row 
       FROM 
       (
        SELECT row_to_json(b) AS second_object 
        FROM (
         SELECT * 
         FROM second_table 
         WHERE client_id = 1 
         ) b 
       ) AS second_row 
      ) 
      ) AS add_info 

     FROM main_table 
     WHERE id = 1 
    ) t; 

但是,這給出了一個額外的對象

{ 
    "id":1, 
    "name":"CRED", 
    "add_info":{ 
     "f1":{"first_object":{"date":"2017-04-17","id":1}}, 
     "f2":{"second_object":{"date":"2017-04-17","id":1}} 
    } 
} 

我能解決這個問題?

回答

1

你可以使用一個公用表表達式:

WITH add_info(first_object, second_object) AS 
    (SELECT 
     (SELECT row_to_json(table1) 
       FROM table1 
       WHERE id = 1 
     ), 
     (SELECT row_to_json(table2) 
       FROM table2 
       WHERE id = 1 
     ) 
    ) 
SELECT row_to_json(t, TRUE) 
FROM (
     SELECT 
     id, name, add_info 
     FROM main_table CROSS JOIN add_info 
     WHERE id = 1 
    ) t; 
+0

好像這是我需要什麼。試圖避免多個「選擇」,但現在似乎無法實現... – Daria