Postgres 9.4:在SELECT上的jsonb数组中包含兄弟列

时间:2015-11-16 04:01:18

标签: json postgresql

如果我有这样的表:

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类似,但所需的输出不同。

1 个答案:

答案 0 :(得分: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"}]