SQL 查询。加入右 table 作为左 table 内的嵌套对象

SQL query. Join right table as nested object inside left table

通读文档后,我找不到关于如何进行这个简单查询的任何信息: 有两个 tables:

    first one is "PACKAGES"
       {
          id: 1,
          name: 'package_1',
          sender_id: 1,
          type: 'shipping'
       }
    second one is "USERS"
       {
          id: 1,
          name: 'user_1'
       }

当我执行 Left、Right Join 或简单的 JOIN 时,它只是将这两个 table 合并为一个。而id,name只是相互覆盖

我需要的是:

       {
          id: 1,
          name: 'package_1',
          sender_id: 1
          type: 'shipping',
          user: {             // second table as nested object
              id: 1,
              name: 'user_1'
          }
       }

我尝试了所有我能找到的东西,例如:

SELECT * FROM packages JOIN users AS user ON packages.sender_id=user.id;"

如何将右 table 作为对象放在左 table 中?

使用to_json呈现查询结果作为嵌套的JSON对象:

select to_json(res) from 
(
  select p.*, to_json(u) "user"
  from packages p 
  inner join users u 
  on p.sender_id = u.id
) res;

结果:

{
  "id": 1,
  "name": "package_1",
  "sender_id": 1,
  "type": "shipping",
  "user": {
    "id": 1,
    "name": "user_1"
  }
}