2017-10-18 61 views
1

TABLE_NAMEËPostgreSQL的組列於JSON包括陣列

id | name | cate | link 
---+------+------+--------- 
1 | a | A | link1 
2 | a | B | link2 
3 | a | B | link3 
4 | b | B | link4 
5 | c | A | link5 
6 | d | A | link6 
7 | e | B | link7 

欲retults:

name | A      | B 
------+------+-------------------+------------ 
a | {id: 1, link: 'link1'} | [{id: 2, link: 'link2'}, {id: 3, link: 'link3'}] 
b |       | [{id: 4, link: 'link4'}] 
c | {id: 5, link: 'link5'} | 
d | {id: 6, link: 'link6'} | 
e |       | [{id: 7, link: 'link7'}] 

的美食字段值只有A,B,C,d。但值是B必須數組

我的實驗失敗

select name, format('{%s}', string_agg(format('"id": "%s", "name": "%s", "link":"%s"', id, name, link), ','))::json as A from elements where cate = 'A' group by name; 
select name, string_to_array(format('[link: "%s", id: "%s", name: "%s"]', link, id, name)) as B from elements where cate = 'B' group by name; 
select name, format('{%s}', string_agg(format('"id": "%s", "name": "%s", "link":"%s"', id, name, link), ','))::json as C from elements where cate = 'C' group by name; 
select name, format('{%s}', string_agg(format('"id": "%s", "name": "%s", "link":"%s"', id, name, link), ','))::json as D from elements where cate = 'D' group by name; 

如果加入其他表P

id | e_id | role_id 
---+------+---------- 
1 | 1 | 100 
2 | 3 | 101 
3 | 4 | 102 
4 | 5 | 103 

結果:

name | checked | A          | B 
-------+---------+---------------------------------------+----------------------------------------------------------------- 
a  | true | {id: 1, link: 'link1', checked: true} | [{id: 2, link: 'link2'}, {id: 3, link: 'link3', checked: true}] 
b  | true |          | [{id: 4, link: 'link4', checked: true}] 
c  | true | {id: 5, link: 'link5', checked: true} | 
d  |   | {id: 6, link: 'link6'}    | 
e  |   |          | [{id: 7, link: 'link7'}] 
+0

有什麼問題你的企圖?你有錯誤嗎?不正確的結果?如果是,哪個? – user5226582

+0

Postgresql版本 – JustMe

+0

@JustMe 9.4+我試着哪個,謝謝。 – 404

回答

0

首先不使用格式函數來創建json字段,PostgreSQL具有解析和創建json字段所需的全部功能。你沒有張貼樣本DDL和數據,但您的查詢應該是這樣的:

select name, 
    json_agg(case cate when 'A' then json_build_object('id',id,'link',link) end) A, 
    json_agg(case cate when 'B' then json_build_object('id',id,'link',link) end) B 
from data group by name 
+0

字段A應該返回json。 – 404

+0

好的,那麼只要做(json_agg(...))[1],或者修改group by – JustMe