2014-02-26 302 views
0

我有表所示:SQL查詢選擇

表:因素

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

您是否收到任何錯誤?你正在選擇'從Fctors'而不是'from Factors' - 你是如何在查詢中做到這一點的? – Alexander

回答

1

無需使用CASELEFT 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; 
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

請嘗試:

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