SQL Developer - 如果第一个连接的输出为空,如何连接到另一个表?

问题描述 投票:0回答:1

情况是这样的。我有 1 个库存表 (inv),我想将其与入库发货表 (inb) 连接在一起,并使用存储在两个表中的值 payment_id。 在“inb”表中存储了“origin”值,对于“inv”表中的每条记录,我想知道“origin”是什么。下面是一个例子:

SELECT
invent.item_id,
invent.location_id,
invent.quantity,
inbound.origin
FROM    
inventory invent LEFT JOIN inbound_shipments inbound on invent.shipment_id = inbound.shipment_id

但有些货件不再位于 inbound_shipments 表中,而是已移至 inbound_shipments_archive。 给定:对于每个shipment_id,inbound_shipments 表或inbound_shipments_archive 表中都有一条记录,因此如果连接列中返回的值为空,则它必须在另一个表中。

我的问题是:我怎样才能以某种方式进行这种连接,使其从这两个表之一获得所需的值(“原点”)到同一列中?

我尝试将两个表的列彼此相邻连接起来。如果没有其他选择,这很有效,并且是一个不错的选择

SELECT
invent.item_id,
invent.location_id,
invent.quantity,
inbound.origin,
inboundarch.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

感谢您的宝贵时间

sql oracle-sqldeveloper
1个回答
0
投票

您可以使用您已经编写的子查询来“选择获胜者”:

SELECT
item_id,
location_id,
quantity,
coalesce(inbound_origin, inboundarch_origin) as origin
FROM
(
SELECT
invent.item_id,
invent.location_id,
invent.quantity,
inbound.origin as inbound_origin,
inboundarch.origin as inboundarch_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
) X
© www.soinside.com 2019 - 2024. All rights reserved.