我有表AccountOpeningDetails
,Customer
,Supplier
。 AccountOpeningDetails
表包含FKCustomerID
和FKSupplierID
。
样本记录如下所示:
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')
要修改哪些内容?
答案 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}}。