【发布时间】:2016-06-28 13:52:33
【问题描述】:
我在使用 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",所以显然我没有正确使用它。
如果有任何提示,我将不胜感激,谢谢!
【问题讨论】:
-
糟糕,在问题中更新了它。现在是 9.5.3。
标签: sql json postgresql jsonb