2015-10-01 49 views
2

假設我有一個裝運部件和收貨部件的表格。我想將我發貨的貨物與我收到的貨物進行比較,並用一個普通貨運編號將其捆綁在一起。SQL:完全外部橫跨兩個層次結合

出貨表

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

應儘量將包括一個RDBMS標籤,SQLSERVER,MySQL的? –

+0

所以,只是爲了確認,是否可以選擇「部分否」加入條件? – gerosalesc

回答

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] 
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

+0

歡迎使用stackoverflow。我想你說得對。你有沒有檢查[** sqlFiddle **](http://sqlfiddle.com/#!6/9a080/2)這有助於當你想顯示一個工作答案。有一個很好的'文本到ddl'函數來幫助準備數據模式。和一個文本輸出,所以你可以粘貼輸出作爲答案,而不是圖片 –

+0

太棒了!我知道有一種基本的連接方式可以實現這一點,但之前沒有理由使用'full join'。 ...這是令人尷尬的,因爲我甚至在我的帖子中使用了「完全外連接」這個詞... –

+0

@Justin,它們(完全連接,完全外連接)都是相同的。所以像左連接/左外連接和右/外連接一樣 –