You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PostgreSQL(Node.js)中将左连接结果转为嵌套列

实现PostgreSQL查询返回嵌套JSON结构

当然可以直接通过PostgreSQL的查询语句生成你想要的嵌套对象结构,不用在Node.js里做后续拼接。PostgreSQL提供了专门的JSON构造函数,刚好适配你的1对1关联场景。

核心实现思路

利用json_build_object()函数将关联表(table2)的字段组装成一个JSON对象,作为主查询结果中的一个字段返回。因为你用的是LEFT JOIN,还可以处理关联表无匹配数据的情况。

具体SQL语句示例

基础版本(保留NULL字段)

SELECT 
  table1.id, 
  table1.name, 
  table1.other_table_id,
  -- 把table2的字段组装成嵌套JSON对象
  json_build_object(
    'id', table2.id,
    'name', table2.name,
    'date', table2.date
  ) AS other_table
FROM table1 
LEFT JOIN table2 ON table1.other_table_id = table2.id 
ORDER BY table1.name;

这个查询返回的other_table字段会是一个JSON对象,当table2没有匹配数据时,对象内的字段值为NULL。

优化版本(无匹配时返回空对象)

如果希望关联表无匹配时返回{}而不是带NULL的对象,可以用COALESCE()函数处理:

SELECT 
  table1.id, 
  table1.name, 
  table1.other_table_id,
  COALESCE(
    json_build_object(
      'id', table2.id,
      'name', table2.name,
      'date', table2.date
    ),
    '{}'::json
  ) AS other_table
FROM table1 
LEFT JOIN table2 ON table1.other_table_id = table2.id 
ORDER BY table1.name;

简化版本(直接转换整行)

如果需要table2的所有字段,也可以用row_to_json()直接将table2的行转换为JSON对象:

SELECT 
  table1.id, 
  table1.name, 
  table1.other_table_id,
  row_to_json(table2) AS other_table
FROM table1 
LEFT JOIN table2 ON table1.other_table_id = table2.id 
ORDER BY table1.name;

注意这个方式会包含table2的所有字段,如果只需要特定字段,还是用json_build_object()更精准。

与node-postgres的适配

node-postgres会自动将PostgreSQL返回的JSON类型解析为JavaScript对象,所以你拿到的查询结果直接就是你期望的嵌套结构,不需要额外处理。

内容的提问来源于stack exchange,提问作者Jesse Finnegan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 13:46:29