我试图从 PostgreSQL 查询返回一个带有嵌套数组的对象,我该怎么做。?这是我迄今为止尝试过的方法,有人可以指导我吗?
SELECT d.id as distributor_id,
d.name,
json_agg(json_build_object('route_id', r.id, 'route_name', r.name,'shops',
json_agg((select * from retailers where retailers."distributorId" = d.id and retailers."routeId" = r.id)) )) as route
FROM users U
INNER JOIN tsi_distributors td ON U.user_id = td."userUserId" AND td.delete_at IS NULL
INNER JOIN distributors d ON td."distributorId" = d.id AND d.delete_at IS NULL
LEFT JOIN routes r on td.id = r."distributorId" AND r.delete_at IS NULL
WHERE U.user_id = 'TSI_84826'
GROUP BY d.id
这会引发错误。 subquery must return only one column
绑定返回这样的对象
[
{
distributor_id: 1,
name: 'Distributor_1',
route: [
{
route_id: 1,
route_name: 'Route 1',
shops: [
{
id: 1,
name: 'shop 1',
},
{
id: 2,
name: 'shop 2',
},
],
},
{
route_id: 2,
route_name: 'Route 2',
shops: [
{
id: 3,
name: 'shop 3',
},
],
},
],
},
];
答案 0 :(得分:0)
您错误地使用了 json_agg:
尝试将 json_agg 转移到子选择中,例如:
( select json_agg(to_json(retailers))
from retailers
where retailers."distributorId" = d.id
and retailers."routeId" = r.id)