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'}]
有什麼問題你的企圖?你有錯誤嗎?不正確的結果?如果是,哪個? – user5226582
Postgresql版本 – JustMe
@JustMe 9.4+我試着哪個,謝謝。 – 404