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

在Ecto中关联表无对应条目时返回0的实现方法

优化单查询获取所有地点的指定产品库存

可以通过一次Ecto查询实现需求,彻底避免原方案的N+1查询问题,核心思路是利用**左连接(left_join)**保留所有地点记录,再用coalesce函数将不存在库存时的null值替换为0。

完整实现代码

# 定义查询,获取所有地点及其对应指定产品的库存(无库存则返回0)
query = 
  from l in Location,
    left_join: s in Stock,
    on: l.id == s.location_id and s.product_id == ^product_id,
    select: %{location: l, quantity: coalesce(s.quantity, 0)}

# 执行一次查询,得到所有结果
result = Repo.all(query)

代码说明

  • left_join:确保所有location记录都会被返回,无论是否存在对应的stock条目
  • coalesce(s.quantity, 0):当stock条目不存在时,s.quantity会是null,这个函数会将其替换为0,正好匹配需求中“无对应条目返回0”的规则
  • 整个逻辑仅执行一次数据库查询,相比原方案循环每个地点做多次查询,性能提升非常明显

简化输出(仅需地点ID和库存)

如果不需要完整的location结构体,只需要地点ID和库存数量,可以调整select部分:

query = 
  from l in Location,
    left_join: s in Stock,
    on: l.id == s.location_id and s.product_id == ^product_id,
    select: %{location_id: l.id, quantity: coalesce(s.quantity, 0)}

Repo.all(query)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:55:57