表:因素
FactorID SellerID ContractorID
---------------------------------
1 -1 2
2 1 -1
3 -1 1
4 2 -1
表:卖家
SellerID SellerName
---------------------
1 SellerA
2 SellerB
3 SellerC
4 SellerD
表承包商:
ContractorID ContractorName
-------------------------------
1 W
2 X
3 Y
4 Z
我希望查询返回如下:
FactorID SellerID ContractorID ContractorName SellerName
------------------------------------------------------------------
1 -1 2 X NULL
2 1 -1 NULL SellerA
3 -1 1 W NULL
4 2 -1 NULL SellerB
这是我的查询,但没有正常工作:
SELECT Factos.* ,
Seller.sellerName AS sellerName ,
Contractor.Contractor AS contractorName
FROM Fctors ,
Seller ,
Contractor
WHERE Seller.SellerID = CASE WHEN Factors.ContrarID = -1 THEN Factors.SellerID
ELSE ''
END
AND Contractor.ContractorID = CASE WHEN Factors.SellerID = -1 THEN Factors.ContractorID
ELSE ''
END
答案 0 :(得分:1)
一个简单的JOIN语句应该提供所需的结果而不需要任何CASE语句
SELECT f.*, s.sellerName as sellerName, c.Contractor as contractorName
FROM Factors f
LEFT OUTER JOIN Sellers s ON(f.SellerId=s.SellerId)
LEFT OUTER JOIN Contractors c ON(f.ContractorId=c.ContractorId)
答案 1 :(得分:1)
请尝试:
SELECT a.*, b.SellerName, c.ContractorName
FROM
Factors A LEFT JOIN Sellers b on a.SellerID=b.SellerID
LEFT JOIN Contractors c on a.ContractorID=c.ContractorID
答案 2 :(得分:1)
我认为您只需使用查询即可获得该结果,请查看以下查询
SELECT F.FactorID, S.SellerID, C.ContractorID, C.ContractorName, S.SellerName FROM FACTORS F LEFT JOIN SELLERS S ON F.SellerID = S.SellerID
LEFT JOIN CONTRACTORS C ON F.ContractorID = C.ContractorID
答案 3 :(得分:1)
SELECT Factors.FactorID,Sellers.SellerID AS SellerID ,
Contractors.ContractorID AS ContractorID,
Contractors.ContractorName AS ContractorName,
Sellers.SellerName AS SellerName
FROM Factors LEFT JOIN Sellers ON Factors.FactorID=Sellers.SellerID
LEFT JOIN Contractors ON Factors.FactorID=Contractors.ContractorID
答案 4 :(得分:1)
Left Outer join
就是您所需要的一切
select f.FactorID, f.SellerID, f.ContractorID, c.ContractorName, s.SellerName
from Factors f left outer join Sellers s on f.SellerID = s.SellerID
left outer join Contractors c on f.ContractorID = c.ContractorID
答案 5 :(得分:1)
无需使用CASE
。 LEFT OUTER JOIN
应该足够了。
应该这样做:
SELECT f.FactorID,
f.SellerID,
f.ContractorID,
c.ContractorName,
s.SellerName
FROM Factors f
LEFT OUTER JOIN Sellers s
ON f.SellerID = s.SellerID
LEFT OUTER JOIN Contractor c
ON f.SellerID = c.SellerID
ORDER BY f.FactorID ASC;