SQL:跨两个层次结构的完全外部联接

时间:2015-10-01 02:40:27

标签: sql join outer-join full-outer-join

我们说我有一张货物上的零件表和收据上的零件。我希望将我发运的货物与我收到的货物相匹配,并以共同的货件编号捆绑在一起。

货件表

SHIPMENT NO    PART NO
 1              A
 1              B
 2              A
 2              C

收据表

SHIPMENT NO    PART NO
 1              A
 1              C
 2              B
 3              A

期望的结果

SHIP. SHIP. NO    SHIP. PART NO    RPT. SHIP. NO    RPT. PART NO
 1                 A                1                A
 1                 B                1                NULL
 1                 NULL             1                C
 2                 A                2                NULL
 2                 NULL             2                C
 NULL              NULL             3                A

因此,我们的想法是,有一个完整的外部联接,显示所有不同的货件编号以及货件和收据的相应部件号,但将它们匹配在一起。即使零件编号不匹配,复杂功能仍然会加入装运编号。

基本上有两个连接条件,其中一个是完全可选的。

我确定解决方案很简单,但我不知道如何在不使用工会的情况下做到这一点。

2 个答案:

答案 0 :(得分:4)

试试这个

CREATE TABLE Shipment ([SHIPMENT NO] int, [PART NO] varchar(1))    
INSERT INTO Shipment ([SHIPMENT NO], [PART NO])
VALUES
    (1, 'A'),
    (1, 'B'),
    (2, 'A'),
    (2, 'C')
;
CREATE TABLE Receipt ([SHIPMENT NO] int, [PART NO] varchar(1));    
INSERT INTO Receipt  ([SHIPMENT NO], [PART NO])
VALUES
    (1, 'A'),
    (1, 'C'),
    (2, 'B'),
    (3, 'A')
;

SELECT 
     X.ShipmentShipNO AS 'SHIP. SHIP. NO'   
    ,s.[PART NO] AS 'SHIP. PART NO'
    ,X.ReceiptShipNO AS 'RPT. SHIP. NO'
    ,r.[PART NO] AS 'RPT. PART NO'

FROM Shipment s
FULL OUTER JOIN Receipt r ON s.[SHIPMENT NO] = r.[SHIPMENT NO] AND s.[PART NO] = r.[PART NO]
FULL OUTER JOIN 
                (
                    SELECT DISTINCT
                        s.[SHIPMENT NO] AS'ShipmentShipNO'
                        ,r.[SHIPMENT NO] AS'ReceiptShipNO'
                        FROM Shipment s
                        FULL JOIN Receipt r ON s.[SHIPMENT NO] = r.[SHIPMENT NO]
                )X ON r.[SHIPMENT NO] = X.ReceiptShipNO OR s.[SHIPMENT NO] = X.ShipmentShipNO
ORDER BY 3


DROP TABLE Shipment
DROP TABLE Receipt

enter image description here

答案 1 :(得分:1)

使用FULL JOIN

<强> SQL Fiddle Demo

SELECT S.*, R.*
FROM Shipment S 
FULL JOIN Receipt R
 ON S.[SHIPMENT NO] = R.[SHIPMENT NO]
AND S.[PART NO] = R.[PART NO]