如何根据外键NULL标准获取行?

时间:2013-11-27 10:06:26

标签: sql-server

我有表AccountOpeningDetailsCustomerSupplierAccountOpeningDetails表包含FKCustomerIDFKSupplierID

样本记录如下所示:

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出现时CustomerName应出现,FKSupplierID为空,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')

要修改哪些内容?

1 个答案:

答案 0 :(得分: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这个混乱的INNER JOiN条件“合并”到AccountOpening表格中的{{1}}。