2013-11-27 44 views
1

我有表AccountOpeningDetails,Customer,SupplierAccountOpeningDetails表包含FKCustomerIDFKSupplierID如何根據外鍵NULL條件獲取行?

樣品記錄下面可以看到:

FKCustomerID  FKSupplierID   Particulars   Debit   Credit 
26     NULL     Test1     6000.00   NULL 
NULL    15     Test2     NULL   8000.00 

我想在這兩個記錄的客戶和供應商的相應名字的意思是輸出應該象下面這樣:

FKCustomerID CustomerName  FKSupplierID  SupplierName   Particulars   
26    UserA    NULL         Test1     
NULL        15    UserB    Test2     

由於看到上面有FKCustomerID目前應該出現CustomerNameFKSupplierID爲空應該沒有名稱SupplierName,反之亦然。

這裏是我的查詢:

SELECT 
    aod.FKCustomerID, aod.FKSupplierID, aod.Particulars, aod.Debit, aod.Credit 
FROM 
    AccountOpeningDetails aod  
WHERE 
    aod.FKAccountOpeningID = (SELECT ID FROM AccountOpening WHERE VoucherNo = '1') 

怎麼辦在對其進行修改?

回答

0

好吧,如果你想顯示一旦客戶,一旦供應商的基礎上,FK是否爲空或不是,您需要使用兩個LEFT OUTER JOIN結構:

SELECT 
    aod.FKCustomerID, c.CustomerName, aod.FKSupplierID, s.SupplierName, 
    aod.Particulars, aod.Debit, aod.Credit 
FROM 
    dbo.AccountOpeningDetails aod  
INNER JOIN 
    dbo.AccountOpening ao ON aod.FKAccountOpeningID = ao.ID 
LEFT OUTER JOIN 
    dbo.Customer c ON aod.FKCustomerID = c.CustomerID 
LEFT OUTER JOIN 
    dbo.Supplier s ON aod.FKSupplierID = s.SupplierID 
WHERE 
    ao.VoucherNo = '1' 

我也「合併」是凌亂的WHERE條件,你已經在AccountOpening表上INNER JOiN

+1

完美!工作就像一個魅力:-) –

+0

有沒有辦法不使用外部聯接?僅在一行中表示整個查詢? –

+0

@ user2738231:沒有,沒有辦法在一行中寫這個 - 你確實需要JOIN--沒有辦法 –