jsonb对象数组和列的合并困难

时间:2016-05-17 19:00:06

标签: sql json postgresql jsonb

我有一张桌子

Visitor: (id, signup_up, sessions, email, custom_fields)

其中custom_fields是格式为

的JSON对象的jsonb数组

CustomField: ( field, value )示例:(domain, www.somedomain.com)

我想在signed_up, sessions, email数组中取CustomField列及其值和custom_fields json对象,并将它们合并到名为data的第3个字段中相同的CustomField结构,即。每个条目的格式为field: value

实施例

给定这些行

id | sessions | email              | custom_fields
---------------------------------------------------------------
1  | 3        | test@gmail.com      [{ field: domain, value: "www.hello.com" }, { field: type, value: "Customer" }]
---------------------------------------------------------------
2  | 5        | another@gmail.com   [{ field: domain, value: "www.other.com" }, { field: type, value: "Customer" }]

我想得到

id | fields
-----------------------
1  | [{sessions: 3, email: test@gmail.com, domain: "www.hello.com", type: "Customer"}]
----------------------
2  | [{sessions: 5, email: another@gmail.com, domain: "www.other.com", type: "Customer"}]

关于如何实现这一点的任何想法?

非常感谢任何帮助

1 个答案:

答案 0 :(得分:5)

示例数据(这应该是问题的一部分,而不是答案;请注意正确的json语法):

show/hide function

提示1.使用$('#searchField').keyup(function(){ var valThis = $(this).val().toLowerCase(); $('.thumbnail') .hide() // reset display val of .thumbnail .filter(function(){ // get items with search-text only var pTxt = $('p',this).text().toLowerCase(); return ( pTxt.indexOf(valThis) != -1 ) ? this : '' ; }) .show('fast'); // show items with search-text }); 并在create table visitor (id int, sessions int, email text, custom_fields jsonb); insert into visitor values (1, 3, 'test@gmail.com', '[{"field": "domain", "value": "www.hello.com" }, {"field": "type", "value": "Customer"}]'), (2, 5, 'another@gmail.com', '[{"field": "domain", "value": "www.other.com" }, {"field": "type", "value": "Customer"}]'); jsonb_array_elements()列中选择fieldvalue的json值:

key

提示2.使用value将这些对(select id, sessions, email, elem->>'field' as key, elem->>'value' as value from visitor, jsonb_array_elements(custom_fields) elem; id | sessions | email | key | value ----+----------+-------------------+--------+--------------- 1 | 3 | test@gmail.com | domain | www.hello.com 1 | 3 | test@gmail.com | type | Customer 2 | 5 | another@gmail.com | domain | www.other.com 2 | 5 | another@gmail.com | type | Customer (4 rows) )聚合到json对象中:

jsonb_object_agg()

最终查询。添加(连接)从列key, valueselect id, jsonb_object_agg(key, value) from ( select id, sessions, email, elem->>'field' as key, elem->>'value' as value from visitor, jsonb_array_elements(custom_fields) elem ) s group by id, sessions, email order by id; id | jsonb_object_agg ----+------------------------------------------------- 1 | {"type": "Customer", "domain": "www.hello.com"} 2 | {"type": "Customer", "domain": "www.other.com"} (2 rows) 构建的json对象,并使用所有对象构建一个json数组:

session

还有一个提示(或技巧):

email