我在使用Postgresql将记录数组转换为JSON时遇到了问题。
版本: psql(PostgreSQL)9.5.3
当前查询:
SELECT c.id, (select array(
select (cp.id,cp.position)
from contactposition cp
where cp.contact_id_id = c.id -- join on the two tables
)
) as contactpositions
from contacts c;
表contacts
中的联系人可以从contactposition
表分配许多职位。
结果是这样的:
| id (integer) | contactpositions (record[]) |
|--------------|----------------------------------------------------------------------|
| 5 | {"(21171326,\"Software Developer\")","(21171325,Contractor)" (...)"} |
但我希望它是这样的:
| id (integer) | contactpositions (record[]) |
|--------------|----------------------------------------------------------------------|
| 5 | [{"id": 21171326, "position": "Software Developer", "id": 21171325, "position": "Contractor", (...)] |
我知道有几个辅助功能,例如array_to_json
,但我无法让它工作。
我试过了:
SELECT c.id, array_to_json(select array(
select (cp.id,cp.position)
from contactposition cp
where cp.contact_id_id = c.id
)
) as contactpositions
from contacts c;
但它抛出:ERROR: syntax error at or near "select"
,显然我没有正确使用它。
感谢任何提示,谢谢!
答案 0 :(得分:4)
使用jsonb_build_object()
和jsonb_agg()
:
select c.id, jsonb_agg(jsonb_build_object('id', cp.id, 'position', cp.position))
from contacts c
join contactposition cp on c.id = cp.contact_id
group by 1;