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

SQL Developer:左连接结果为NULL时如何关联另一表获取字段

合并入库运单主表与归档表的origin字段到同一列

针对你的需求,有两种更优的实现方式,避免返回两个独立的origin列:

方案一:使用COALESCE函数合并字段

利用COALESCE函数返回第一个非空值的特性,直接将两个左连接得到的origin字段合并为一列。因为每个shipment_id仅存在于主表或归档表中的一个,所以只会有一个origin有有效值,另一个为NULL,COALESCE会自动取到正确的那个值。

SELECT
  invent.item_id,
  invent.location_id,
  invent.quantity,
  COALESCE(inbound.origin, inboundarch.origin) AS origin
FROM
  inventory invent
LEFT JOIN inbound_shipments inbound
  ON invent.shipment_id = inbound.shipment_id
LEFT JOIN inbound_shipments_archive inboundarch
  ON invent.shipment_id = inboundarch.shipment_id

方案二:先合并运单表再关联库存表

先通过UNION ALL将主表和归档表的记录合并(两个表结构一致且无重复shipment_id),再将合并后的结果作为子查询与库存表左连接。这种方式逻辑更清晰,只需要一次关联操作。

SELECT
  invent.item_id,
  invent.location_id,
  invent.quantity,
  combined.origin
FROM
  inventory invent
LEFT JOIN (
  SELECT shipment_id, origin FROM inbound_shipments
  UNION ALL
  SELECT shipment_id, origin FROM inbound_shipments_archive
) combined
  ON invent.shipment_id = combined.shipment_id

方案对比

  • 若仅需合并origin字段,两种方案都适用;COALESCE方式改动最小,适合在原有查询基础上快速调整。
  • 若后续需要获取运单表的其他字段,UNION ALL合并表的方式更易于扩展,无需重复写多个左连接和COALESCE。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:48:15