2015-11-16 93 views
0

jsonb陣列兄弟列。如果我有這樣的一個表:的Postgres 9.4:包括在SELECT

office_id int 
employees jsonb 

和數據看起來是這樣的:

1 
[{ "name" : "John" }, { "name" : "Jane" }] 

有沒有一種簡單的方法查詢這樣的結果是這樣的:

office_id,employees 
1,[{ "name" : "John", "office_id" : 1 }, { "name" : "Jane", "office_id" : 1 }] 

數據。例如,看看這個sqlfiddle:http://sqlfiddle.com/#!15/ac37b/1/0

結果其實應該是這樣的:

id employees 
1 [{ "name" : "John", "office_id" : 1 }, { "name" : "Jane", "office_id" : 1 }] 
2 [{ "name" : "Jamal", "office_id" : 1 }] 

我一直在讀通過json functions而且好像這是可能的,但我似乎無法弄清楚。我寧願不必在每個嵌套對象上存儲office_id。

注意:這與my other question about jsonb arrays類似,但所需的輸出不同。

+0

你能提供更清晰的樣本數據? 'CREATE TABLE'和'INSERT'語句?現在,這看起來像'SELECT office_id,employees FROM my_table' –

回答

0

我不確定您是從Postgres表還是json對象表中進行選擇。做一個正常的查詢並將其轉換爲json可以使用json_agg()來完成。

這是一個正常的查詢:

ao_db=# SELECT * FROM record.instance; 
        id     | created_by |   created_on   | modified_by |   modified_on   
--------------------------------------+------------+-------------------------------+-------------+------------------------------- 
18d8ca56-87b6-11e5-9c15-48d22415d991 | sysop  | 2015-11-10 23:19:47.181026+09 | sysop  | 2015-11-10 23:19:47.181026+09 
190a0e86-87b6-11e5-9c15-48d22415d991 | sysop  | 2015-11-10 23:19:47.56517+09 | sysop  | 2015-11-10 23:19:47.56517+09 
57611c9c-87b6-11e5-8c4b-48d22415d991 | admin  | 2015-11-10 23:21:32.399775+09 | admin  | 2015-11-10 23:22:27.975266+09 
(3 行) 

這裏是()通過json_agg通過了相同的查詢:

ao_db=# WITH j AS (SELECT * FROM record.instance) SELECT json_agg(j) FROM j; 
                          json_agg                       
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
[{"id":"18d8ca56-87b6-11e5-9c15-48d22415d991","created_by":"sysop","created_on":"2015-11-10T23:19:47.181026+09:00","modified_by":"sysop","modified_on":"2015-11-10T23:19:47.181026+09:00"}, + 
    {"id":"190a0e86-87b6-11e5-9c15-48d22415d991","created_by":"sysop","created_on":"2015-11-10T23:19:47.56517+09:00","modified_by":"sysop","modified_on":"2015-11-10T23:19:47.56517+09:00"}, + 
    {"id":"57611c9c-87b6-11e5-8c4b-48d22415d991","created_by":"admin","created_on":"2015-11-10T23:21:32.399775+09:00","modified_by":"admin","modified_on":"2015-11-10T23:22:27.975266+09:00"}]