2016-06-28 26 views
0

我在使用Postgresql將記錄數組轉換爲JSON時遇到問題。在Postgresql中將記錄數組轉換爲JSON

版本: PSQL(PostgreSQL的)9.5.3

當前查詢:從表contacts

SELECT c.id, (select array(
     select (cp.id,cp.position) 
     from contactposition cp 
     where cp.contact_id_id = c.id -- join on the two tables 
     ) 
    ) as contactpositions 
from contacts c; 

聯繫可以從contactposition表中分配多個位置。

結果是這樣的:

| id (integer) | contactpositions (record[])           | 
|--------------|----------------------------------------------------------------------| 
| 5   | {"(21171326,\"Software Developer\")","(21171325,Contractor)" (...)"} | 

但我想它是這樣的:

| id (integer) | contactpositions (record[])           | 
|--------------|----------------------------------------------------------------------| 
| 5   | [{"id": 21171326, "position": "Software Developer", "id": 21171325, "position": "Contractor", (...)] | 

我知道像array_to_json幾個輔助函數,但我可以」讓它工作。

我已經試過:

SELECT c.id, array_to_json(select array(
      select (cp.id,cp.position) 
      from contactposition cp 
      where cp.contact_id_id = c.id 
      ) 
     ) as contactpositions 
from contacts c; 

但它拋出:ERROR: syntax error at or near "select",所以很明顯我沒有使用它的權利。

我會感謝任何提示,謝謝!

+0

Postgres的版本? – klin

+0

糟糕,在問題中更新了它。它是9.5.3。 – primoz

回答

4

使用jsonb_build_object()jsonb_agg()

select c.id, jsonb_agg(jsonb_build_object('id', cp.id, 'position', cp.position)) 
from contacts c 
join contactposition cp on c.id = cp.contact_id 
group by 1; 
+0

完美!非常感謝你! – primoz