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

如何在PostgreSQL中通过子查询或连接获取多表全量数据?

解决PostgreSQL中INNER JOIN仅返回匹配行的问题

你当前使用的INNER JOIN只会返回所有连接条件都匹配的行,这就是为什么只能得到关联数据的原因。要保留主表(比如recipe)的所有记录,同时关联其他表的匹配数据(无匹配时对应字段显示NULL),可以把所有INNER JOIN替换为LEFT JOIN(左外连接):

select 
  r.name, 
  r.description, 
  tags.name as tags, 
  rb.ingredient_id, 
  mb.name as macros 
from recipe r 
left join recipe_tags tags on r.id = tags.recipe_id 
left join recipe_breakdown rb on r.id = rb.recipe_id 
left join recipe_master_breakdown mb on r.id = mb.recipe_id 
limit 50;

说明:

  • LEFT JOIN会保留左表(这里是recipe)的所有行,右表没有匹配记录时,对应字段会填充NULL。
  • 调整了后续表的连接条件,直接用r.id关联而不是依赖tags.recipe_id,避免因为recipe_tags无匹配时,后续连接丢失recipe的记录。

如果你的需求是保留所有关联表的全部记录(包括未关联到recipe的行),可以使用FULL OUTER JOIN,但这种场景相对少见,示例如下:

select 
  r.name, 
  r.description, 
  tags.name as tags, 
  rb.ingredient_id, 
  mb.name as macros 
from recipe r 
full outer join recipe_tags tags on r.id = tags.recipe_id 
full outer join recipe_breakdown rb on coalesce(r.id, tags.recipe_id) = rb.recipe_id 
full outer join recipe_master_breakdown mb on coalesce(r.id, tags.recipe_id, rb.recipe_id) = mb.recipe_id 
limit 50;

这里用coalesce函数处理可能的NULL值,确保连接条件能匹配到存在的recipe_id。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:31:21