【问题标题】:subquery must return only one column Postgrsql子查询必须只返回一列 Postgresql
【发布时间】:2021-04-29 17:23:57
【问题描述】:

我正在尝试从 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',
          },
        ],
      },
    ],
  },
];

【问题讨论】:

    标签: json postgresql


    【解决方案1】:

    你错误地使用了 json_agg:

    1. 不应将子查询的结果集用作 json_agg(或任何其他聚合函数)的参数
    2. json_agg 接受 json 作为参数,它不会将任何内容转换为 json。

    尝试将 json_agg 转移到子选择中,例如:

    ( select json_agg(to_json(retailers)) 
      from retailers 
      where retailers."distributorId" = d.id 
        and retailers."routeId" = r.id)
    

    【讨论】:

      猜你喜欢
      • 2019-12-02
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 2022-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多